这是我编写的代码,而不是编辑特定的行,新名称在最后被添加... 请帮帮我......
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();
}
答案 0 :(得分:7)
除非您不更改行的(字节)长度,否则您需要重写整个文件,并在适当的位置添加更改的行。这实际上只是对当前代码的一个简单更改。首先,在没有FileWriter
的情况下初始化append
(因为不想要只追加到文件的末尾,这就是您现在正在做的事情)。
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
完成后别忘了关闭所有文件句柄!