How to delete a line from a text file with java using scanner

前端 未结 1 477
失恋的感觉
失恋的感觉 2020-12-12 06:00

I have text file called BookingDetails.txt

inside the file there\'s a line of records

Abid  Akmal  18/11/2013  0122010875  Grooming  Zalman  5  125.0         


        
相关标签:
1条回答
  • 2020-12-12 06:52

    Try something like this. The code reads each line of a file. If that line doesn't contain the name, The line will be written to a temporary file. If the line contains the name, it will not be written to temp file. In the end the temp file is renamed to the original file.

    File inputFile = new File("myFile.txt");   // Your file  
    File tempFile = new File("myTempFile.txt");// temp file
    
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
    
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter firstName");
    String firstName = scanner.nextLine();
    System.out.println("Enter lastName");
    String lastName = scanner.nextLine();
    
    String currentLine;
    
    while((currentLine = reader.readLine()) != null) {
    
        if(currentLine.contains(firstName) 
             && currentLine.contains(lastName)) continue;
    
        writer.write(currentLine);
    }
    
    writer.close();
    boolean successful = tempFile.renameTo(inputFile);
    System.out.println(successful);
    
    0 讨论(0)
提交回复
热议问题