java bufferedReader 读出来为什么都是空的?
PHP中文网
PHP中文网 2017-04-18 09:36:10
0
3
429

帮朋友提问:

        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中文网

认证高级PHP讲师

reply all(3)
大家讲道理

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.

巴扎黑

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...

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!