我有一个程序可以读取文本文件,我想删除某一行。现在我的解决方案是创建另一个文件并将除了要删除的行之外的每一行写入该新文件。然后我删除原始文件并重命名新文件,使其具有相同的名称。我想知道是否有更简单的方法。
public void deleteLine(int index){
try{
File file = new File("Original File location");
Scanner reader = new Scanner(file);
File temp = new File("New File location");
PrintWriter writer = new PrintWriter(temp);
String holder;
for (int i=0;i<index;i++){
writer.println(reader.nextLine());
}
holder=reader.nextLine();
while (reader.hasNextLine()==true){
writer.println(reader.nextLine());
}
writer.flush();
reader.close();
writer.close();
if (!file.delete()){
System.out.println("Can't delete file");
return;
}
if (!temp.renameTo(file)){
System.out.println("Can't rename file");
}
}
catch(IOException e){
System.out.println("File not found");
}
}