我使用以下代码片段逐行读取文件并将其写入另一个文件中。我的输入文件大约包含 13000
行,但它生成的输出文件仅包含 12000
行
public class FileReadWrite {
public static void main(String args[]) {
FileReader input = null;
BufferedReader br = null;
BufferedWriter printer = null;
try {
input = new FileReader("input.txt");
File output = new File("output.txt");
br = new BufferedReader(input);
printer = new BufferedWriter(new FileWriter(output));
String s;
while((s = br.readLine()) != null){
printer.write(s);
printer.newLine();
}
}
catch(FileNotFoundException e) {
System.err.println("File not found. Please scan in new file.");
}
catch(Exception e)
{
System.err.println("Exception occured"+e);
}
}
添加此代码片段后,它工作正常
finally{
try
{
input.close();
br.close();
printer.close();
}
catch(Exception e)
{
}
}
有什么原因吗?
最佳答案
我建议进行二进制传输,它有很多优点
- 您无需对文本进行解码/编码,因此不必担心编码会破坏您的文本
- 您不必担心匹配新的行分隔符,它可以是
\r
或\n
或\r\n
- 您不需要复制到缓冲区或从缓冲区复制。所有复制都是在 native 代码/内存中完成的。
- 代码更短,速度更快
try-with-resource block 为您关闭资源/
try (FileChannel from = new FileInputStream(fromFile).getChannel();
FileChannel to = new FileOutputStream(toFile).getChannel()) {
from.transferTo(0, from.size(), to);
} catch (IOException ioe) {
ioe.printStackTrace();
}
关于java - 使用 FileReader 和 BufferedReader 时忘记用户 .close(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656595/