简体   繁体   中英

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).

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.

// 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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