我想读取一个文件并创建该文件的副本,但是我的代码只写了文件的最后一行。我该如何做,以便每当我调用write()
时,它都会写入新行。我想为重复项创建一个新文件,因此无法将true添加到FileWriter
构造函数。
这是我的代码:
//Create file reader
BufferedReader iReader = new BufferedReader(new FileReader(args[1]));
//Create file writer
BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));
String strLine;
//reading file
int iterate = 0;
while((strLine = iReader.readLine()) != null) {
instructions[iterate] = strLine;
}
//creating duplicate
for(int i = 0; i < instructions.length; i++) {
if(instructions[i] != null) {
oWriter.write(instructions[i]);
oWriter.newLine();
} else {
break;
}
}
try {
iReader.close();
oWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
您没有递增iterate
int iterate = 0;
while((strLine = iReader.readLine()) != null)
{
instructions[iterate] = strLine;
iterate++;
}
关于java - BufferedWriter覆盖自身,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19522253/