RandomAccessFile類的主要功能是完成隨機讀取功能,可以讀取指定位置的內(nèi)容,F(xiàn)ile類只是針對文件本身進行操作的 .
public RandomAccessFile(File file, String mode) throws FileNotFoundException.
第一個參數(shù)是指操作的是哪個文件,第二個參數(shù)具有兩種模式,分別為:
- r:讀模式
- w:只寫
- rw:讀寫模式,如果此文件不存在,則自動創(chuàng)建
例子:
long offset = 1024 * 1024;
File file = new File("/Users/sunow/a.txt");
byte[] fileData = file.getBytes();
File tmpFile = new File(uploadDirPath, tempFileName);
// 讀寫模式
RandomAccessFile tmpRaf = new RandomAccessFile(tmpFile, "rw");
FileChannel fileChannel = temRaf.getChannel();
// 通道映射
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, offset, fileData);
mappedByteBuffer.put(fileData);