简体   繁体   English

在Java中编辑文本文件

[英]Editing a text file in java

I want add few strings to a text file in a particular location. 我想在特定位置的文本文件中添加一些字符串。 I have used BufferedReader to read the text file. 我已经使用BufferedReader读取文本文件。 Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter . 然后,我将字符串添加到特定位置,然后使用BufferedWriter将修改后的文本写入新的临时文件。

Then I deleted the old file and renamed the temp file to old file name. 然后,我删除了旧文件,并将临时文件重命名为旧文件名。 This works sometimes and does not work sometimes. 这有时起作用,有时不起作用。 The delete() function sometimes does not delete the file. delete()函数有时不会删除文件。 I have closed all the BufferedWriter 's, but the problem still occurs sometimes. 我已经关闭了所有BufferedWriter ,但是有时仍然会出现问题。

Code: 码:

public boolean cart(String uname, String item) throws IOException {
    File file = new File("C:\\$$$$.tmp");
    if (!file.exists()) {
        file.createNewFile();
    }
    FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    File fileop = new File("C:\\value.text");
    FileReader fr = new FileReader(fileop.getAbsoluteFile());
    BufferedReader br = new BufferedReader(fr);
    String line;
    while((line = br.readLine()) != null) {
        String val[] = line.split(",");
        if (val[0].equals(uname)) {
            String linenew = line + item + "&";
            bw.append(linenew);
            bw.newLine();
            bw.flush();
        } else {
            bw.append(line);
            bw.newLine();
            bw.flush();
        }
    }
    br.close();
    bw.close();
    fileop.delete();
    file.renameTo(fileop);
    return true;
 }

I found the answer by myself after spending one full day of searching.. 经过一整天的搜索,我自己找到了答案。

Answer is: 答案是:

It is enough to close the bufferedReader but also the fileReader.. 关闭bufferedReader以及fileReader就足够了。

fr.close(); fr.close(); should be inserted after br.close(); 应该在br.close()之后插入;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM