简体   繁体   中英

How to add new line in the middle of txt file in java

I have to modify a text file in java. eg this is the file before modify

line
line
line 
line
line 
line

and after it should look like:

line
line
this is another 
line
line
line
line

So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.

A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file. But is there any way to read and modify a file like I want using the same class in java? thx!

You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.

Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.

Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.

The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.

Try this:

public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
    File file = new File(filename); 
    File temp = File.createTempFile("temp-file-name", ".tmp");
    BufferedReader br = new BufferedReader(new FileReader( file ));
    PrintWriter pw =  new PrintWriter(new FileWriter( temp ));
    String line;
    int lineCount = 0;
    while ((line = br.readLine()) != null) {
        pw.println(line);
        if(lineCount==lineno){
            pw.println(text);
        }
        lineCount++;
    }
    br.close();
    pw.close();
    file.delete();
    temp.renameTo(file);
}

The code is not tested, but it should work, you can improve the code with several validations and exception handling

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