如何更新或删除.txt文件中的特定行?

时间:2015-06-22 13:01:44

标签: java

我已经有了将数据插入文本文件并进行搜索的方法。现在我想要更新'并且'删除'选定的记录。

这是我到目前为止所做的,

setReadOnly(false)

有人可以帮我这个吗? 我想要方法:

Connection

提前致谢! :)

2 个答案:

答案 0 :(得分:1)

我举一个例子,我找到了。在这个例子中,我将替换一行内的字符串。在我的情况下,我可以看到从txt中读取。

/ ******

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

        while ((line = file.readLine()) != null) input += line + '\n';

        file.close();

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

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

        // check if the new input is right
        System.out.println("----------------------------------"  + '\n' + input);

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

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

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

* /

结果:

原件:

原始文本文件内容:

做菜啊 喂狗0 清理我的房间1 输出:

做菜啊 喂狗0

清理我的房间1

做菜1 喂狗0 清理我的房间1

近期输出:

做菜1(已经改变) 喂狗0 清理我的房间1

也许这个例子对你有帮助。

问候!

答案 1 :(得分:0)

将数据读取到字符串。使用string.replace(forDelte,"")。然后只需重写为txt文件。

相关问题