Java 替换文本文件中的行 [英] Java Replace Line In Text File

查看:32
本文介绍了Java 替换文本文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I replace a line of text found within a text file?

我有一个字符串,例如:

I have a string such as:

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

}

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

By the way, I want to replace ONLY the line that was read. NOT the entire file.

推荐答案

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

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

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('
');
        }
        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("----------------------------------
" + 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");   
}

<小时>

原始文本文件内容:


Original Text File Content:

洗碗0
喂狗0
打扫了我的房间1

Do the dishes0
Feed the dog0
Cleaned my room1

输出:

洗碗0
喂狗0
打扫了我的房间1
----------------------------------
洗碗1
喂狗0
打扫了我的房间1

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

新的文本文件内容:

洗碗1
喂狗0
打扫了我的房间1

Do the dishes1
Feed the dog0
Cleaned my room1

<小时>

注意,如果文本文件是:


And as a note, if the text file was:

洗碗1
喂狗0
打扫了我的房间1

Do the dishes1
Feed the dog0
Cleaned my room1

并且您使用了方法 replaceSelected("Do the盘", "1");,它不会改变文件.

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.

由于这个问题非常具体,我会在这里为未来的读者添加一个更通用的解决方案(基于标题).

Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// 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('
');
        }
        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 替换文本文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆