【问题标题】:Null coming at end of file while using BufferedReader and PrintWriterNull 在使用 BufferedReader 和 PrintWriter 时出现在文件末尾
【发布时间】:2021-09-06 11:25:16
【问题描述】:

我有一个 Java 程序,它从一个文件中读取数据并将相同的数据写入另一个文件:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;

public class MyClass{

    public static void main(String args[]) {
        try {

             StringBuilder res = new StringBuilder();

             File file = new File("myxml.xml");

             BufferedReader br = new BufferedReader(new FileReader(file));

             while (br.read() != -1) {
                 res.append(br.readLine());
                 res.append(System.lineSeparator());
             }

             PrintWriter out = new PrintWriter("file.xml");
             out.print(res);
             out.close();
       } catch(Exception e) {
             e.printStackTrace();
         }

     }
}

原始 XML 如下所示:

<data>
 ...... some entries ..... 
</data>

然而,新的 xml 是这样来的:

data>
...... some entries .....
/data>
null

如果我不使用行分隔符,所有数据都将进入一行。我在这里错过了什么?

【问题讨论】:

    标签: java xml bufferedreader stringbuilder printwriter


    【解决方案1】:

    问题是br.read() 已经占用了行的第一个字符。然后在调用readLine() 时会丢失此数据。

    像这样逐行读取数据:

    String line;
    while ((line = br.readLine()) != null) {
        // do stuff with the read content
    }
    

    但是,您实际上不需要为此任务使用StringBuilder。您可以在阅读后立即使用PrintWriter#println() 打印每一行。

    例子:

    public static void main(String[] args) {
        File file = new File("myxml.xml");
        try (PrintWriter out = new PrintWriter("file.xml");
                BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    在示例中,PrintWriterBufferedReader 在 try-with-resources 块中创建,因此会自动关闭。

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 1970-01-01
      • 2012-05-30
      • 2016-11-10
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      相关资源
      最近更新 更多