Question

At first, what I am trying to do is to return a value by Scanner which involves a File doc without passing to another word. Here is my source code:

public static void deleteLine() throws IOException{
    File mainFile = new File("H:\\EcD\\data.txt");
    File tempFile = new File("H:\\EcD\\tempFile");
    Scanner input = new Scanner(mainFile);
    String lineNumberToDelete = "4";
    while(input.hasNextLine()){
        if(!input.next().startsWith(lineNumberToDelete))
            System.out.println(input.nextLine());
    }
    input.close();      
}

I have not used any undeclared variables, so i thought it was okay to just write down the method. Actually my main aim is to delete a spesific line from a textfield which is designed as this:

1) Line 1 Code
2) Line 2 Code
3) Line 3 Code
4) Line 4 Code
5) Line 5 Code
Était-ce utile?

La solution

Change it to this and your problem will be solved.

public static void deleteLine() throws IOException{
    File mainFile = new File("H:\\EcD\\data.txt");
    File tempFile = new File("H:\\EcD\\tempFile");
    Scanner input = new Scanner(mainFile);
    String lineNumberToDelete = "4";
    while(input.hasNextLine()){
        String line = input.nextLine();
        if(!line.startsWith(lineNumberToDelete))
            System.out.println(line);
    }
    input.close();

}

Then replace the System.out.println with writing to the target file.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top