简体   繁体   English

我想打开一个文本文件并在java中编辑一个特定的行

[英]I want to open a text file and edit a specific line in java

This is code i Have written instead of editing a particular line new name gets appened at the last... please help me out.... 这是代码我写的而不是编辑特定的行新名称在最后得到...请帮帮我....

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();

}

Unless you aren't changing the (byte) length of the line, you need to rewrite the whole file, adding the changed line where appropriate. 除非您不更改行的(字节)长度,否则需要重写整个文件,并在适当的位置添加更改的行。 This is actually just a simple change from your current code. 这实际上只是对当前代码的一个简单更改。 First, initialize your FileWriter without the append (since you don't want to just append to the end of the file, which is what you're doing now). 首先,初始化FileWriter没有append (因为你不想只是附加到文件,这是你现在正在做什么的结束)。

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

Then, either read the whole file into memory (if the file is small enough) or else write a temp file as you go and then copy it over when you're done. 然后,将整个文件读入内存(如果文件足够小),或者在你去的时候写一个临时文件,然后在完成后复制它。 The second way is more robust, and requires less code changing; 第二种方法更健壮,需要更少的代码更改。 just modify your while loop to write every line, modified or not. 只需修改您的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

Don't forget to close all your file handles when you're done! 完成后,别忘了关闭所有文件句柄!

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

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