帮朋友提问:
File file1 = new File("D:\\a.txt");
File file2 = new File("D:\\a.txt");
FileWriter fileWriter2 = new FileWriter(file2);
FileReader fileReader = new FileReader(file1);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter2);
String length = null;
while((length=bufferedReader.readLine())!=null) {
System.out.println(length);
bufferedWriter2.write(length);
}
fileReader.close();
bufferedWriter2.close();
这段代码为什么读到的length都是null?
我个人觉得是因为file1和file2同时打开a.txt,会出现读写冲突,导致都出来的都是null,不知大家怎么看?
Java IO operates based on byte stream. Of course, the character stream is also completed through byte stream at the bottom layer. There is an implicit pointer to represent the current reading or writing position.
@iMouseWu is right, because
FileOutputStream
对象被创建时会执行一个native
的open()
操作,如果没有指定append
属性为true
, the pointer will move to the beginning of the file, which is equivalent to clearing the file operation.Of course the questioner uses
FileWiter
也是通过FileOutputStream
to achieve this.In addition, if you need to read and write files at the same time, it is recommended to use
RandomAccessFile
.I tested it
new FileWriter(file2)
It automatically cleared the file contents...But I checked the document and it did not stipulate that the content can be cleared completely when using new...
FileWriter fileWriter2 = new FileWriter(file2,true);
创建
FileWriter
改append为true