0

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");
            }
        }
Coder
  • 1,917
  • 3
  • 17
  • 33
zamsler
  • 197
  • 13
  • You can check following link. First Answer's second portion may be help you where line is removing from current file and shifting line upward : http://stackoverflow.com/questions/6477762/java-delete-line-from-text-file-by-overwriting-while-reading-it – Abu Sufian Dec 07 '16 at 03:56
  • Possible duplicate of [Find a line in a file and remove it](http://stackoverflow.com/questions/1377279/find-a-line-in-a-file-and-remove-it) – Gurwinder Singh Dec 07 '16 at 03:57

0 Answers0