[英]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()
两次,witch占用了两行,但是每次只将其中之一添加到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'
符号都不在输出字符串中。 要重新添加分隔符,请取消注释上面代码中的注释行。
您调用了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完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.