如何从 java 中的文件中删除特定文本?

How can i remove a particular text from a file in java?

我试图实现一个简单的程序来从文件中删除特定的文本,但有些方法无法删除它。我正在将整个文件内容读入一个临时文件,从中删除用户输入的字符串并将内容更新为原始文件。 任何帮助将不胜感激。

public class TextEraser{

        public static void main(String[] args) throws IOException  {
            
            
            System.out.print("Enter a string to remove  : ");
            Scanner scanner = new Scanner(System. in);
            String inputString = scanner. nextLine();
            
            // Locate the  file
            File file = new File("/Users/lobsang/documents/input.txt");
            
            //create temporary file 
            
            File temp = File.createTempFile("file", ".txt", file.getParentFile());

            String charset = "UTF-8";
            
            

            try {
                
                // Create a buffered reader
                // to read each line from a file.
                BufferedReader in = new BufferedReader(new FileReader(file));
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));

                String s = in.readLine();

                // Read each line from the file and echo it to the screen.
                while (s !=null) {
                    
                          s=s.replace(inputString,"");
                          s = in.readLine();

                }
                

                writer.println(s);
                
                // Close the buffered reader
                in.close();
                writer.close();
                
                file.delete();
                temp.renameTo(file);
                


            } catch (FileNotFoundException e1) {
                // If this file does not exist
                System.err.println("File not found: " + file);

            
        }

    }

替换为输入字符串后,立即将字符串写入文件。

while (s != null) {
    s = s.replace(inputString, "");
    writer.write(s);
    // writer.newLine();
    s = in.readLine();
}

对于新行,使用 BufferedWriter 代替 PrintWriter,它包含方法 newLine()

writer.newLine();

删除这个

writer.println(s);