java文件操作(待完善)

来源:互联网 发布:淘宝商城女装新款夏装连衣裙 编辑:程序博客网 时间:2024/05/22 09:40

1.读取某路径下的文件;

2.将某目录下文件拷贝到指定路径;



以字节为单位从stream中读取或往stream中写入信息

input/output stream:
1) ByteArrayInputStream/ ByteArrayOutputStream:把内存中的一个缓冲区作为InputStream使用/把信息存入内存中的一个缓冲区中
2) StringBufferInputStream:把一个String对象作为InputStream
3) FileInputStream/ FileOutputStream:把一个文件作为InputStream,实现对文件的读取操作/把信息存入文件中
4) PipedInputStream/PipedOutputStream:实现了pipe的概念,主要在线程中使用
5) SequenceInputStream/SequenceOutputStream:把多个InputStream合并为一个InputStream/把多个OutStream合并为一个OutStream


以Unicode字符为单位从stream中读取或往stream中写入信息:与上有所不同的是前者每次从内存中读取一个字节的信息,而后者每次从内存中读取一个字符。

Reader/Write
1) CharArrayReader/ CharArrayWrite:与ByteArrayInputStream/ByteArrayOutputStream对应
2) StringReader/ StringWrite:与StringBufferInputStream对应
3) FileReader/ FileWrite:与FileInputStream/FileOutputStream对应
4) PipedReader/ PipedWrite:与PipedInputStream/PipedOutputStream对应

    :写入字符串到文件中,成功则返回success字符串

    1. public String writeSomething() {   
    2. try {   
    3.    
    4.  File f = new File(path);   
    5.  PrintWriter out = new PrintWriter(new FileWriter(f));   
    6.  out.print(this.getSomething() + "  
    7. ");   
    8.  out.close();   
    9.  return "Success.";   
    10. } catch (IOException e) {   
    11.  return e.toString();   
    12. }   
    13. }   
    14. }  


java读取文本文件代码

  1. package net.chinaunix.blog.hzm.text;

  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;

  5. public class ReadFile {

  6.     private String path;
  7.     
  8.     
  9.     public ReadFile(String filePath){
  10.         path = filePath;
  11.     }
  12.     
  13.     public String[] openFile() throws IOException{
  14.         
  15.         FileReader fr = new FileReader(path);
  16.         BufferedReader textReader = new BufferedReader(fr);
  17.         
  18.         String[] textData = new String[readLines()];
  19.         int i;
  20.         for(i=0; i < readLines();i++){
  21.             textData[i] = textReader.readLine();
  22.         }
  23.         
  24.         textReader.close();
  25.         
  26.         return textData;
  27.     }
  28.     
  29.     int readLines() throws IOException{
  30.         FileReader fileToRead = new FileReader(path);
  31.         BufferedReader bf = new BufferedReader(fileToRead);
  32.         
  33.         int numberOfLines = 0;
  34.         
  35.         @SuppressWarnings("unused")
  36.         String oneLine;
  37.         while((oneLine = bf.readLine()) != null){
  38.             numberOfLines++;
  39.         }
  40.         bf.close();
  41.         
  42.         return numberOfLines;
  43.         
  44.     }
  45. }



  1. package net.chinaunix.blog.hzm.text;

  2. import java.io.IOException;

  3. public class FileData {

  4.     public static void main(String[] args) throws IOException{
  5.         
  6.         String filePath = "C:/text.txt";
  7.         
  8.         try{
  9.             ReadFile reader = new ReadFile(filePath);
  10.             String[] content = reader.openFile();
  11.             
  12.             int i;
  13.             for(i=0;i<content.length;i++){
  14.                 System.out.println(content[i]);
  15.             }
  16.             
  17.         }catch(IOException e){
  18.             System.out.println("异常信息:" + e.getMessage());
  19.         }
  20.     }
  21. }


java.io.BufferedReader

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

BufferedReader in = new BufferedReader(new FileReader("foo.in")); will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.




java.io.FileReader

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.



但通过FilterInputStream和FilterOutStream的子类,我们可以为stream添加属性。下面以一个例子来说明这种功能的作用。
一个文件中写入数据,我们可以这样操作:
FileOutStream fs = new FileOutStream(“test.txt”);
然后就可以通过产生的fs对象调用write()函数来往test.txt文件中写入数据了。但是,如果我们想实现“先把要写入文件的数据先缓存到内存中,再把缓存中的

数据写入文件中”的功能时,上面的API就没有一个能满足我们的需求了。但是通过FilterInputStream和FilterOutStream的子类,为FileOutStream添加我们所需要的功能。

4. I/O应用的一个例子

import java.io.*;
public class TestIO{
    public static void main(String[] args) throws IOException{
//1.以行为单位从一个文件读取数据
    BufferedReader in =new BufferedReader(new FileReader(\"F:
epalonTestIO.java\"));
    String s, s2 = new String();
    while((s = in.readLine()) != null)
        s2 += s + \"
\";
    in.close();

//1b. 接收键盘的输入
    BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in));
    System.out.println(\"Enter a line:\");
    System.out.println(stdin.readLine());

//2. 从一个String对象中读取数据
    StringReader in2 = new StringReader(s2);
    int c;
    while((c = in2.read()) != -1)
        System.out.println((char)c);
    in2.close();

//3. 从内存取出格式化输入
    try{
        DataInputStream in3 =new DataInputStream(new ByteArrayInputStream(s2.getBytes()));
        while(true)
            System.out.println((char)in3.readByte());
    }
    catch(EOFException e){
        System.out.println(\"End of stream\");
    }

//4. 输出到文件
    try{
        BufferedReader in4 =new BufferedReader(new StringReader(s2)); //把s2当作输入对象
        PrintWriter out1 =new PrintWriter(new BufferedWriter(new FileWriter(\"F:
epalon TestIO.out\")));
        int lineCount = 1;
        while((s = in4.readLine()) != null)
            out1.println(lineCount++ + \":\" + s);
        out1.close();
        in4.close();
    }
    catch(EOFException ex){
        System.out.println(\"End of stream\");
    }

//5. 数据的存储和恢复
    try{
        DataOutputStream out2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(\"F:
epalon Data.txt\")));
        out2.writeDouble(3.1415926);
        out2.writeChars(\"
Thas was pi:writeChars
\");
        out2.writeBytes(\"Thas was pi:writeByte
\");
        out2.close();
        DataInputStream in5 = new DataInputStream(new BufferedInputStream(new FileInputStream(\"F:
epalon Data.txt\")));
        BufferedReader in5br = new BufferedReader(new InputStreamReader(in5));
        System.out.println(in5.readDouble());
        System.out.println(in5br.readLine());
        System.out.println(in5br.readLine());
    }
    catch(EOFException e){
        System.out.println(\"End of stream\");
    }

//6. 通过RandomAccessFile操作文件
    RandomAccessFile rf = new RandomAccessFile(\"F:
epalon rtest.dat\", \"rw\");
    for(int i=0; i<10; i++)
        rf.writeDouble(i*1.414);
    rf.close();

    rf = new RandomAccessFile(\"F:
epalon rtest.dat\", \"r\");
    for(int i=0; i<10; i++)
        System.out.println(\"Value \" + i + \":\" + rf.readDouble());
    rf.close();

    rf = new RandomAccessFile(\"F:
epalon rtest.dat\", \"rw\");
    rf.seek(5*8);
    rf.writeDouble(47.0001);
    rf.close();

    rf = new RandomAccessFile(\"F:
epalon rtest.dat\", \"r\");
    for(int i=0; i<10; i++)
        System.out.println(\"Value \" + i + \":\" + rf.readDouble());
    rf.close();
    }
}

关于代码的解释(以区为单位):
1区中,当读取文件时,先把文件内容读到缓存中,当调用in.readLine()时,再从缓存中以字符的方式读取数据(以下简称“缓存字节读取方式”)。
1b区中,由于想以缓存字节读取方式从标准IO(键盘)中读取数据,所以要先把标准IO(System.in)转换成字符导向的stream,再进行BufferedReader封装。
2区中,要以字符的形式从一个String对象中读取数据,所以要产生一个StringReader类型的stream。
4区中,对String对象s2读取数据时,先把对象中的数据存入缓存中,再从缓冲中进行读取;对TestIO.out文件进行操作时,先把格式化后的信息输出到缓存中,再把缓存中的信息输出到文件中。
5区中,对Data.txt文件进行输出时,是先把基本类型的数据输出屋缓存中,再把缓存中的数据输出到文件中;对文件进行读取操作时,先把文件中的数据读取到缓存中,再从缓存中以基本类型的形式进行读取。注意in5.readDouble()这一行。因为写入第一个writeDouble(),所以为了正确显示。也要以基本类型的形式进行读取。
6区是通过RandomAccessFile类对文件进行操作。 


http://www.diybl.com/course/3_program/java/javajs/20111028/562318.html



26、Math.round(11.5)等於多少? Math.round(-11.5)等於多少? 
Math.round(11.5)==12
Math.round(-11.5)==-11
round方法返回与参数最接近的长整数,参数加1/2后求其floor.

27、String s = new String("xyz");创建了几个String Object? 
两个(一个是“xyx”,一个是指向“xyx”的引用对象s)