I have a program that reads through a text file and I want to delete a certain line. Right now my solution is to create another file and write every line except for the one I want to delete onto that new file. Then I delete the original and rename the new one so it has the same name. I was wondering if there is a simpler way of doing this.
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");
}
}