读写文字不完整?

Reading and writing text is not complete?

从文本文件读取和写入似乎有问题。

虽然有两个不同的文件,但我打印了内容,但它似乎与文本文件中的内容不一样。

我尝试添加 + 和不添加,以及添加 bw.close() 或不添加。我也尝试过使用扫描仪代替,但它没有打印出任何东西。

它能以某种方式改变吗?

  private void readFromFile(File cf2) throws IOException, Exception {

   FileReader fr = new FileReader(cf2);
   try (BufferedReader bw = new BufferedReader(fr)) {
    System.out.println("Wait while reading !");

    while(bw.readLine() != null)
    s1 += bw.readLine();
    System.out.println(s1);
    bw.close();
   } System.out.println("File read !");
  }

您使用了 bw.readLine() 两次, 消耗了两行,但您每次只将其中一行添加到 s1。尝试

String line;
while((line = bw.readLine()) != null)
    s1 += line;
System.out.println(s1);

一半的 readLine 调用用于检查 null 的数据,另一半被添加到 s1。这就是为什么您只获得部分输入的原因。

要修复您的代码,请进行如下循环:

while (true) {
    String s = bw.readLine();
    if (s == null) break;
    s1 += s;
}

但是,这是非常低效的。你最好使用 StringBuffer:

StringBuffer sb = new StringBuffer()
while (true) {
    String s = bw.readLine();
    if (s == null) break;
    sb.append(s);
    // Uncomment the next line to add separators between lines
    // sb.append('\n');
}
s1 = sb.toString();

请注意,您文件中 '\n' 个符号中的 none 个将出现在输出字符串中。要重新添加分隔符,请取消注释上面代码中的注释行。

你调用了 readline() 两次,所以你只得到每隔一行。

  private void readFromFile(File cf2) throws IOException, Exception {

   FileReader fr = new FileReader(cf2);
   try (BufferedReader br = new BufferedReader(fr)) {
       System.out.println("Wait while reading !");
       StringBuilder sb = new StringBuilder();
       String s;
       while((s = br.readLine()) != null) {
           sb.append(s);
       }
       System.out.println(sb.toString());
   }
  System.out.println("File read !");
  }

您不需要关闭 br,因为这是由 try-with-resources 完成的。