search

Home  >  Q&A  >  body text

java bufferedReader 读出来为什么都是空的?

帮朋友提问:

        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,不知大家怎么看?

PHP中文网PHP中文网2810 days ago470

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 09:38:10

    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 对象被创建时会执行一个 nativeopen() 操作,如果没有指定 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.

        public FileWriter(File file, boolean append) throws IOException {
            super(new FileOutputStream(file, append));
        }

    In addition, if you need to read and write files at the same time, it is recommended to use RandomAccessFile.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:38:10

    I tested itnew 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...

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:38:10

    FileWriter fileWriter2 = new FileWriter(file2,true);
    创建FileWriter 改append为true

    reply
    0
  • Cancelreply