Java替换文本文件中的行

标签 java replace line jcheckbox

如何替换文本文件中的一行文本?

我有一个字符串,例如:

Do the dishes0

我想更新它:

Do the dishes1

(反之亦然)

我该如何做到这一点?

ActionListener al = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JCheckBox checkbox = (JCheckBox) e.getSource();
                    if (checkbox.isSelected()) {
                        System.out.println("Selected");
                        String s = checkbox.getText();
                        replaceSelected(s, "1");
                    } else {
                        System.out.println("Deselected");
                        String s = checkbox.getText();
                        replaceSelected(s, "0");
                    }
                }
            };

public static void replaceSelected(String replaceWith, String type) {

}

顺便说一句,我只想替换已读取的行。不是整个文件。

最佳答案

在底部,我有一个替换文件中行的通用解决方案。但首先,这里是手头具体问题的答案。辅助函数:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

然后调用它:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

原始文本文件内容:

Do the dishes0
Feed the dog0
Cleaned my room1

输出:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

新的文本文件内容:

Do the dishes1
Feed the dog0
Cleaned my room1


请注意,如果文本文件是:

Do the dishes1
Feed the dog0
Cleaned my room1

你使用了 replaceSelected("Do the bowls", "1"); 方法, 它不会改变文件。


由于这个问题非常具体,我将在这里为 future 的读者添加一个更通用的解决方案(根据标题)。

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

关于Java替换文本文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039980/

相关文章:

java - 使用分页计算字段的服务器端排序?

java - FATAL EXCEPTION : main, 但 eclipse 没有显示任何错误

c# - 使用 Excel Interop c# 将单词替换为粗体单词

c - 从任何数据函数读取打印行

java - 非 Java 程序员进行 Android 开发的最快途径

java - 如何在 Java 中高效地编写大量/多个敌人的生成和碰撞检测代码

jquery - 我对 jquery 搜索、突出显示并跳转到突出显示的代码有疑问

python - 用列表中的一项替换字符串中的一项

android - 如何在android中动态画线

正则表达式不匹配行