简体   繁体   English

文字读写不完整?

[英]Reading and writing text is not complete?

There seems to be a problem with reading and writing from a textfile. 从文本文件读取和写入似乎存在问题。

While having two different files I printed out the content and it doesn't seem the same as it should be in the textfiles. 虽然有两个不同的文件,但我打印出了内容,但看起来与文本文件中的内容并不相同。

I tried to add + and without, and to add bw.close() or without. 我尝试添加+和不添加bw.close()或不添加。 I tried also to use scanner instead, but it didn't print out anything. 我也尝试使用扫描仪代替,但是它没有打印出任何东西。

Could it be changed somehow ? 可以以某种方式更改吗?

  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 !");
  }

You are using bw.readLine() twice, witch consumes two lines, but you are adding only one of them to s1 each time. 您使用bw.readLine()两次,witch占用了两行,但是每次只将其中之一添加到s1 Try 尝试

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

Half of your readLine calls are used for checking the data for null , the other half get added to s1 . 您的readLine调用中有一半用于检查数据是否为null ,另一半被添加到s1 That's why you get only part of the input. 这就是为什么您只获得部分输入的原因。

To fix your code, make a loop like this: 要修复您的代码,请执行如下循环:

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

However, this is grossly inefficient. 但是,这是非常低效的。 You would be better off using StringBuffer : 您最好使用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();

Note that none of '\\n' symbols from your file would be in the output string. 请注意,文件中的'\\n'符号都不在输出字符串中。 To add separators back, uncomment the commented line in the code above. 要重新添加分隔符,请取消注释上面代码中的注释行。

You call readline() twice, so you only get every second line. 您调用了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 !");
  }

You don't need to close br because that is done by try-with-resources. 您不需要关闭br因为这是通过try-with-resources完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM