如何使用Java中的用户输入从文本文件中删除旧数据

时间:2015-04-14 06:21:42

标签: java text-files

我正在尝试获取用户输入并查看它是否与文本文件中的任何句子匹配。如果是这样我想删除这句话。我的意思是我有搜索实现到目前为止我需要的是帮助删除句子并可能重写到文本文件。我不熟悉Java。任何帮助,将不胜感激。

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. 



     }

        }

    }
}

1 个答案:

答案 0 :(得分:1)

我认为您无法同时读取和写入文件,因此,创建一个临时文件并将替换文本的所有数据写入新文件,然后将该临时文件移动到原始文件中。 我附上了代码,希望这有帮助。

        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);