0

I have a function that adds, searches, and deletes lines from a text file. The Search works irrelevant of case and has a .contains which allows it to work on less than the whole line. The delete function only deletes the exact match. I'm accessing an outside .txt file which is saving the changes that are made.

I tried duplicating my search code, but was unable to produce the same result. I'd also like to completely remove the line so that my table remains clean looking if I don't delete that last entry, but that's less important.

    System.out.println("What would you like to delete");
    Scanner deleteScanner = new Scanner(System.in);
    String deleteInput = deleteScanner.nextLine();
    try{
          File file = new File("contacts.txt");
          File temp = File.createTempFile("file", ".txt", 
          file.getParentFile());
          BufferedReader reader = new BufferedReader(new 
          InputStreamReader(new FileInputStream(file)));
          PrintWriter writer = new PrintWriter(new 
          OutputStreamWriter(new FileOutputStream(temp)));
         for (String line; (line = reader.readLine()) != null;) {
            line = line.replace(deleteInput, "");
            writer.println(line);
        }
  reader.close();
  writer.close();
  file.delete();
  temp.renameTo(file);
    } catch (IOException e){
         e.printStackTrace();
    }

I feel like .contains should work but I haven't been able to make it function as intended.

  • 1
    Possible duplicate of [Find a line in a file and remove it](https://stackoverflow.com/questions/1377279/find-a-line-in-a-file-and-remove-it) – Giddy Naya Aug 08 '19 at 22:08

1 Answers1

1

You could get all file lines easier by using:

List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset());

After that you can simple iterate thru the lines List and delete the whole line if it contains deleteInput:

for (String line : lines) {
    if (line.contains(deleteInput)) {
        lines.remove(line);
    }
}

If there is a need to find the occupies ignoring case you can use toLowerCase() before each check.

Blind Kai
  • 514
  • 5
  • 14