简体   繁体   English

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

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

I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it.我试图实现一个简单的程序来删除文件中的特定文本,有些是无法删除它的。 I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.我正在将整个文件内容读入临时文件,从中删除用户输入字符串并将内容更新为原始文件。 Any help would be highly appreciated.任何帮助将不胜感激。

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

            
        }

    }

After replace with input string, write string immediate in file.替换为输入字符串后,立即在文件中写入字符串。

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

For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()对于新行,使用 BufferedWriter 代替 PrintWriter,它包含方法 newLine()

writer.newLine();

Remove this删除这个

writer.println(s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM