I am trying to delete a line of text from a text file without copying to a temporary file. I try to do this using Printwriter and Scanner, and skipping them at the same time, the author writes that the scanner reads and overwrites each line with the same thing until it reaches the line that I want to Delete. Then I promote the scanner, but not the writer, and continue as before. Here is the code:
But first the parameters: My file names are numbers, so this will read 1.txt or 2.txt, etc., and therefore f indicates the file name. I convert it to String in the constructor for the file. Int n is the index of the row I want to delete.
public void deleteLine(int f, int n){ try{ Scanner reader = new Scanner(new File(f+".txt")); PrintWriter writer = new PrintWriter(new FileWriter(new File(f+".txt")),false); for(int w=0; w<n; w++) writer.write(reader.nextLine()); reader.nextLine(); while(reader.hasNextLine()) writer.write(reader.nextLine()); } catch(Exception e){ System.err.println("Enjoy the stack trace!"); e.printStackTrace(); } }
This gives me weird errors. It says “NoSuchElementException” and “line not found” in the stack trace. It points to different lines; it seems that any of the calls to nextLine () can do this. Is it possible to delete a row this way? If so, what am I doing wrong? If not, why? (BTW, just in case you want it, the text file is about 500 lines. I don’t know if it matters as big or even important.)
java text-files printwriter
Shelley
source share