java.io.BufferedReader和java.io.BufferedWriter类各拥有8192字符的缓冲区。当BufferedReader在读取文本文件时,会先尽量从文件中读入字符数据并置入缓冲区,而之后若使用read()方法,会先从缓冲区中进行读取。如果缓冲区数据不足,才会再从文件中读取,使用BufferedWriter时,写入的数据并不会先输出到目的地,而是先存储至缓冲区中。如果缓冲区中的数据满了,才会一次对目的地进行写出。
- public static void main(String[] args) throws Exception{
-
- 1 File file = new File("d:\\test\\20150401_001");
- 2 File fil1 = new File("d:\\test\\20150401_001");
- 3 BufferedReader reader = new BufferedReader( new FileReader( file));
- 4 BufferedWriter writer = new BufferedWriter( new FileWriter( fil1));
- StringBuffer buffer = new StringBuffer();
- String tmp = reader.readLine();
- while( tmp != null ){
- buffer.append(tmp.trim() + "\n");
- tmp = reader.readLine();
- }
- System.out.println(buffer.toString());
- }
复制代码
当3,4行代码执行时,第4行代码会把路径下的文件设置为空文件。后面代码while不再进入,打印出来为'';
如果想对一个文件进行操作,输出后文件路径,文件名保持不变,应该如例:
- BufferedReader reader = new BufferedReader( new FileReader( new File(fileName)));
-
-
- StringBuffer buffer = new StringBuffer();
-
- String tmp = reader.readLine();
- while( tmp != null ){
- buffer.append(tmp.trim() + "\n");
- tmp = reader.readLine();
- }
- BufferedWriter writer = new BufferedWriter( new FileWriter( new File(fileName)));
-
- writer.write( );
复制代码
|
|