阅读和写作文字不完整?

时间:2017-01-29 07:26:47

标签: java filereader

从文本文件中读取和写入似乎存在问题。

虽然有两个不同的文件我打印出内容,但它看起来与文本文件中的内容相同。

我尝试添加+和不添加,并添加bw.close()或不添加。我也尝试使用扫描仪,但它没有打印出来。

可能会以某种方式改变吗?

Description->belongsTo('Transaction');
Transaction->hasMany('Description');

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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'个符号都不在输出字符串中。要重新添加分隔符,请取消注释上面代码中的注释行。

答案 2 :(得分:1)

你两次调用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完成的。