8

I wish to write data to a file at different offsets. Example, at 0th position, at (size/2)th position, at (size/4)th position etc. size represent the file size of the file meant to be created. Is this possible without creating different file parts and joining them?

1

3 Answers 3

8

Well you can write to anywhere you like in a file using RandomAccessFile - just use seek to get to the right place, and start writing.

However, this won't insert bytes at those places - it will just overwrite them (or add data at the end if you're writing past the end of the current file length, of course). It's not clear whether that's what you want or not.

0
0

What you are looking for are Random access files. From the official sun java tutorial site -

Random access files permit nonsequential, or random, access to a file's contents. To access a file randomly, you open the file, seek a particular location, and read from or write to that file.

This functionality is possible with the SeekableByteChannel interface. The SeekableByteChannel interface extends channel I/O with the notion of a current position. Methods enable you to set or query the position, and you can then read the data from, or write the data to, that location. The API consists of a few, easy to use, methods:

position – Returns the channel's current position
position(long) – Sets the channel's position
read(ByteBuffer) – Reads bytes into the buffer from the channel
write(ByteBuffer) – Writes bytes from the buffer to the channel
truncate(long) – Truncates the file (or other entity) connected to the channel

and an example, which is provided there -

String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);

ByteBuffer copy = ByteBuffer.allocate(12);

try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
    // Read the first 12
    // bytes of the file.
    int nread;
    do {
        nread = fc.read(copy);
    } while (nread != -1 && copy.hasRemaining());

    // Write "I was here!" at the beginning of the file.
    // See how they are moving back to the beginning of the
    // file?
    fc.position(0);
    while (out.hasRemaining())
        fc.write(out);
    out.rewind();

    // Move to the end of the file.  Copy the first 12 bytes to
    // the end of the file.  Then write "I was here!" again.
    long length = fc.size();

    // Now see here. They are going to the end of the file.
    fc.position(length-1);

    copy.flip();
    while (copy.hasRemaining())
        fc.write(copy);
    while (out.hasRemaining())
        fc.write(out);
} catch (IOException x) {
    System.out.println("I/O Exception: " + x);
}
0

If this isn't a huge file you can read the entire thing and than edit the array:

public String read(String fileName){
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        String everything = sb.toString();
    } finally {
        br.close();
    }
}

public String edit(String fileContent, Byte b, int offset){
    Byte[] bytes = fileContent.getBytes();
    bytes[offset] = b;
    return new String(bytes);
]

and then write it back to the file (or just delete the old one and write the byte array to a new file with the same name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.