0

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.

public static void searchFile(String s) throws FileNotFoundException {
    File file = new File("data.txt");
    Scanner keyboard = new Scanner(System.in);

    // String lines = keyboard.nextLine();
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
        final String lineFromFile = scanner.nextLine();
        if (lineFromFile.contains(s)) {
            // a match!
            System.out.println(lineFromFile + "is found already");

            System.out.println("would you like to rewrite new data?");
            String go = keyboard.nextLine();
            if (go.equals("yes")) {

                // Here i want to remove old data in the file if the user types yes then rewrite new data to the file. 



     }

        }

    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file. I have appended code bellow, hope this helps.

        File f = new File("D:\\test.txt");
        File f1 = new File("D:\\test.out");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String s = "test";
        BufferedReader br = new BufferedReader(new FileReader(f));
        PrintWriter pr = new PrintWriter(f1);
        String line;
        while((line = br.readLine()) != null){
            if(line.contains(s)){
                System.out.println(line + " is found already");

                System.out.println("would you like to rewrite new data?");
                String go = input.readLine();
                if(go.equals("yes")){
                    System.out.println("Enter new Text :");
                    String newText = input.readLine();
                    line = line.replace(s, newText);
                }
            }

            pr.println(line);
        }
        br.close();
        pr.close();
        input.close();
        Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
niks
  • 204
  • 1
  • 4
  • This does not remove the data in the file, instead it writes over the old data. Still trying to remove old data then write –  Apr 14 '15 at 23:12