简体   繁体   中英

Write to file at particular index

I need to write to a file at a particular index position. BufferedWriter and PrintWriter does not allow writing to an index. How do I go about achieving this?

Basically what i want to do is if a file contains an empty line at the EOF then i need to write at that position, else insert a new line and write. Copying the contents of the file to a temporary file and then deleting the original file and then again renaming the temporary file to the original file's name isn't an option.

Thanks

You need to use a RandomAccessFile .

Using this class, you can go to a specific location using the seek(long) method and write using the different write methods.

In the case of your particuliar problem, the best solution weems to be to use a RandomAccessFile and navigate to the end of your file. Check if this is a new line, write, close.

Given is the method to write content at particular position.

Lets say my file is Test.txt and content is as follow

Hello 
How are you
Today is Monday

now you want to write " hi " after hello. So the offset for " hi " will be "5".

Method is:

filename = "test.txt";
offset = 5;
byte[] content = ("\t hi").getBytes();

private void insert(String filename, long offset, byte[] content) throws IOException {

    RandomAccessFile r = new RandomAccessFile(filename, "rw");
    RandomAccessFile rtemp = new RandomAccessFile(filename+"Temp", "rw");
    long fileSize = r.length(); 
    FileChannel sourceChannel = r.getChannel();
    FileChannel targetChannel = rtemp.getChannel();
    sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
    sourceChannel.truncate(offset);
    r.seek(offset);
    r.write(content);
    long newOffset = r.getFilePointer();
    targetChannel.position(0L);
    sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
    sourceChannel.close();
    targetChannel.close();
    rtemp.close();
    r.close();

}

The output will be:

Hello hi
How are you
Today is Monday

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