我想打开一个文本文件并在java中编辑一个特定的行 [英] I want to open a text file and edit a specific line in java

查看:83
本文介绍了我想打开一个文本文件并在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();

}


推荐答案

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

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

然后,将整个文件读入内存(如果文件足够小)或者写一个你去的临时文件,然后在你完成后复制它。第二种方式更强大,并且需要更少的代码更改;只需修改你的while循环来编写每一行,修改与否。

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!

这篇关于我想打开一个文本文件并在java中编辑一个特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆