编辑: 实际的错误是File1内容完全复制到File2 +中,带有其他一些文本行。文件很大。因此,必须相应地重新提出问题。但是,答案是正确的。它解决了这个问题。额外的行被删除。
代码段:
public class ReadAFile {
public static void main(String[] args) throws IOException {
File file = new File("primes.txt");
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("primesFile.txt")));
char[] buffer = new char[1024];
int read;
while ((read = bufferedReader.read(buffer)) > 0) {
writer.write(buffer, 0, buffer.length);
}
writer.close();
bufferedReader.close();
}
}
答案 0 :(得分:0)
while ((read = bufferedReader.read(buffer)) > 0) {
writer.write(buffer, 0, buffer.length);
}
通常的错误。你假设read()填充缓冲区。见Javadoc。您需要在write方法中使用读取计数:
while ((read = bufferedReader.read(buffer)) > 0) {
writer.write(buffer, 0, read);
}
但除非你确定该文件是文本,否则你应该使用流,而不是读者和作者。