简体   繁体   中英

Alternative to RandomAccessFile.setLength()

In case the underlining file system does not support RandomAccessFile.setLength(..) operation, is there any equivalent file operation in Java , eg writing empty content until certain size?

Thanks in advance.

Increasing the size can be done quite simply:

File file = new File(filename);
long destSize = 1000000;
long orgSize = file.length();
if (destiSize > orgSize) {
    long diff = destSize - orgSize;
    try (FileOutputStream fos = new FileOutputStream(file, true)) {
        byte[] buf = new byte[4096];
        while (diff > 0) {
            int len = (int) Math.min(buf.length, diff);
            fos.write(buf, 0, len);
            diff -= len;
        }
    }
}

Truncating is harder, because there is no method in RandomAccessFile or other classes, I'm aware of. The "simplest" approach is to create a new file, copy the original data to it, until destSize is reached, delete the old file and rename the new file to the name of the old one.

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