3

这是我编写的代码,而不是编辑特定的行,最后添加了新名称...请帮帮我....

PrintWriter writer = new PrintWriter(new BufferedWriter(
        new FileWriter("d:\\book.txt", true)));

BufferedReader br = null;
FileReader reader = null;
try {
    reader = new FileReader("d:\\book.txt");
    br = new BufferedReader(reader);
    String line;
    System.out.println((";;;;;;;;;;;;;;;;" + request
            .getParameter("hname")));
    System.out.println(request.getParameter("book"));
    while ((line = br.readLine()) != null) {

        if (request.getParameter("hname").equals(line)) {
            line = line.replace(request.getParameter("hname"),
                    request.getParameter("book"));

            writer.println(line);

            writer.close();
        }
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
}finally{
    reader.close();

}
4

1 回答 1

7

除非您不更改行的(字节)长度,否则您需要重写整个文件,并在适当的地方添加更改的行。这实际上只是对您当前代码的简单更改。首先,在没有的情况下初始化你FileWriterappend(因为你不想只是追加到文件的末尾,这就是你现在正在做的)。

PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.txt")));

然后,要么将整个文件读入内存(如果文件足够小),要么随时编写一个临时文件,然后在完成后将其复制过来。第二种方式更健壮,并且需要更少的代码更改;只需修改您的 while 循环以编写每一行,无论是否修改。

// Open a temporary file to write to.
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.temp")));

// ... then inside your loop ...

while ((line = br.readLine()) != null) {
    if (request.getParameter("hname").equals(line)) {
        line = line.replace(request.getParameter("hname"),
                request.getParameter("book"));
    }
    // Always write the line, whether you changed it or not.
    writer.println(line);
}

// ... and finally ...

File realName = new File("d:\\book.txt");
realName.delete(); // remove the old file
new File("d:\\book.temp").renameTo(realName); // Rename temp file

完成后不要忘记关闭所有文件句柄!

于 2013-06-20T16:39:26.097 回答