且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java替换文本文件中的行

更新时间:2023-02-23 14:36:24

经过测试和工作

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"));
        String line;
        StringBuffer inputBuffer = new StringBuffer();

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

        file.close();

        System.out.println(inputStr); // check that it's inputted right

        // this if structure determines whether or not to replace "0" or "1"
        if (Integer.parseInt(type) == 0) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        }
        else if (Integer.parseInt(type) == 1) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        } 

        // check if the new input is right
        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");   
}






原始文本文件内容:


Original Text File Content:


菜肴0


喂狗0

清理我的房间1

Do the dishes0
Feed the dog0
Cleaned my room1

输出:


做菜0 br>
喂狗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 br>
清理我的房间1

Do the dishes1
Feed the dog0
Cleaned my room1

您使用的方法 replaceSelected(做菜 ,1);
它不会改变文件。

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