【问题标题】:How can i remove a particular text from a file in java?如何从java文件中删除特定文本?
【发布时间】:2020-11-01 12:56:57
【问题描述】:

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

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

            
        }

    }

【问题讨论】:

  • 您将输入字符串替换为空字符串,可以,并将其存储到s。然后你阅读下一行并再次覆盖s。你没有对被替换的行做任何事情。您需要将替换后的字符串写入输出文件,因此请在 s=s.replace(inputString,""); 之后添加一行。
  • 所以我相信 s=s.replace(inputstring,"")。 - 如果用户输入字符串在该行中,则将其替换为空字符串...然后最后我将该行写入带有 writer.println(s) 的临时文件..我是否缺少某些东西...可以你请给我更多的细节..很失落

标签: java file java.util.scanner filereader


【解决方案1】:

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

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

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

writer.newLine();

删除这个

writer.println(s);

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2020-03-05
    • 2023-03-23
    • 2022-12-13
    相关资源
    最近更新 更多