Java:从文件中删除字符串的出现次数

时间:2015-05-07 15:41:47

标签: java

我正在尝试创建一个程序,从文本文件中删除所有出现的指定String。我正在尝试使用Java GUI来获取用户的输入。我正面临着这个问题请参考以下两个类。

import java.io.*;
import java.util.*;

public class MyRemover {
    public static void main(String[] args) throws Exception {
        // Check if the file exists
        String fileName = "myFile.txt";
        File sourceFile = new File(fileName);
        if (!sourceFile.exists()) {
          System.out.println("Source file " + fileName + " not exist");
          System.exit(2);
        }

        // Read text from the file and save it in a string builder
        Scanner input = new Scanner(sourceFile);
        StringBuilder sb = new StringBuilder();

        String lineSeparator = System.getProperty("line.separator");
        boolean firstLine =  true;
            String toBeRemove = "test";
        while (input.hasNext()) {
            String s1 = input.nextLine();
            String s2 = s1.replaceAll(toBeRemove, "");
            if (firstLine) {
                sb.append(s2);
                firstLine = false;
            } else {
                sb.append(lineSeparator + s2);
            }
        }

        input.close();

        // Write back to the file
        PrintWriter output = new PrintWriter(sourceFile);
        output.println(sb.toString());
        output.close();
    }
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class RemoverFrame extends JFrame {
    private JLabel prompt; // label to prompt user to enter text
    private JLabel display; // label to display text
    private JTextField textEntered; // textfield to enter text

    // constructor sets up GUI
    public RemoverFrame() {
        super("Text Removal");
        prompt = new JLabel("Enter text to remove:");
        textEntered = new JTextField(10); // textfield for text entered

        // register anonymous action listener
        textEntered.addActionListener(
            new ActionListener() {// anonymous inner class
                public void actionPerformed(ActionEvent e) {
                    String texted = textEntered.getText();
                    System.out.println(MyRemover(texted));
                }
            } //end call to addActionListener
        ); //end anonymous inner class

        display = new JLabel("Text removed:");

        add(prompt, BorderLayout.NORTH); // north region
        add(textEntered, BorderLayout.CENTER); // center region
        add(display, BorderLayout.SOUTH); // south region
    } // end RemoverFrame constructor
} // end class RemoverFrame

1 个答案:

答案 0 :(得分:0)

如果您的唯一目的是替换文本文件中所有文本的出现,请尝试:

Path path = Paths.get("C:/test.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("text_to_replace", "");
Files.write(path, content.getBytes(charset));

你完成了!