Features and application scenarios of RandomAccessFile

RandomAccessFile

  1. RandomAccessFile directly inherits the Object class and implements the DataInput and DataOutput interfaces
  2. It can be used as both an input stream and an output stream
package com.ntt.sts;

import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {
    
    

    @Test
    public void randomAccessFileTest() throws IOException {
    
    
        RandomAccessFile randomAccessFile = new RandomAccessFile(new File("test1.png"),"r");
        RandomAccessFile randomAccessFile1 = new RandomAccessFile(new File("三刀流索隆.jpg"),"rw");

        byte[] bytes = new byte[1024];
        int len;
        while((len = randomAccessFile.read(bytes)) != -1){
    
    
            randomAccessFile1.write(bytes,0,len);
        }
        randomAccessFile.close();;
        randomAccessFile1.close();
    }
}
  1. Features
  • When specifying the path, if the file does not exist, it will be created automatically
  • If you repeatedly add data to the file, it will overwrite the original data (overwrite from front to back) instead of appending data.
  • Provides the seek() method. This method calls the pointer to implement the file insertion operation. Other streams either use the append() method to append to the end of the file, or overwrite it directly.
  1. Application scenario,
    the download function of resuming the download of Thunderbolt, two temporary files will be created before downloading, one is an empty file with the same size as the downloaded file, and the other is a file that records the location of the file pointer. Each time it is paused, The pointer of the last time will be saved, and then when downloading at a breakpoint, it will continue to download from the place where it was last time, thus realizing the function of downloading or uploading at a breakpoint.

Guess you like

Origin blog.csdn.net/weixin_43941676/article/details/108431198