之前的IO流都是顺序访问
RandomAccessFile对随机访问文件的读取和写入(可用于文件分割)
迅雷下载视频快速的原因:用多个客户端对下载分割好的视频段,再用并发多线程同时下载,最后合并视频段
Construction | Description |
---|---|
RandomAccessFile(File file, String mode) | 创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。 |
RandomAccessFile(String name, String mode) | 创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。 |
mode参数主要有: “r”(可读)、“rw”(可读可写)
用字节流方式操作即可:
Modifier and Type | Function | Description |
---|---|---|
int | read(byte[] b, int off, int len) | 将最多 len 个数据字节从此文件读入 byte 数组。 |
void | write(byte[] b, int off, int len) | 将 len 个字节从指定 byte 数组写入到此文件,并从偏移量 off 处开始。 |
void | seek(long pos) | 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。 |
pos - 从文件开头以字节为单位测量的偏移量位置,在该位置设置文件指针。
Test1测试指定起始位置,读取其后所有内容
public static void Test1() throws IOException {
RandomAccessFile raf = new RandomAccessFile("abc.txt", "r");
// 随机读取(例如从第二个位置读取)
raf.seek(2);
// 读取(因为是字节流,所以读取方式和之前分段读取的操作一样)
byte[] flush = new byte[1024];
int len = -1;
while(-1 != (len = raf.read(flush))) {
System.out.println(new String(flush, 0, len));
}
raf.close();/*需要释放*/
}
(原文本)***********************************
hello!abc.
(结果)**************************************
llo!abc.
===============================
结论:对照原文本和结果发现确实是从第二个字节开始打印,少了he
Test2测试指定起始位置,循环读取分段内容
public class RandomAccessFileTest {
public static void main(String[] args) throws IOException {
// ①需要分块文件
File file = new File("abc.txt");
// ②计算文件块数
long len = file.length();/*未分割的文件大小*/
int blockLen = 30;/*块大小*/
/*块数 = 文件大小 / 块大小*/
int num = (int)Math.ceil(len*1.0/blockLen);
/*强制转型(int)-向上取整( ceiling天花板)-强制转型(double)*/
System.out.println("文件大小:" +len);
System.out.println("分割文件块数:" + num);
// ③分割文件
int beginPos = 0;/*设置变量保存可变的起始位置*/
int actualSize = (int)(blockLen>len?len:blockLen);/*设定当前文件块大小*/
for(int i = 0; i < num; i++ ) {
beginPos = i*blockLen;
if(i == num-1) {/*最后一块文件的大小 = 未分割的文件大小*/
actualSize = (int)len;
}else {/*不是最后一块,当前文件块大小= 块大小; 未分割的文件大小 = 未分割的文件大小 - 当前文件块大小*/
actualSize = blockLen;
len -= actualSize;
}
System.out.println(i + "-->" + beginPos + "-->" + actualSize);
Test1(i,beginPos,actualSize);
}
}
// Test1分块雏形,①起始位置、③实际大小
public static void Test1(File file, int beginPos,int actualSize) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r");
// 随机读取
raf.seek(beginPos);
// 读取(因为是字节流,所以读取方式和之前分段读取的操作一样)
byte[] flush = new byte[1024];
int len = -1;
while(-1 != (len = raf.read(flush))) {
/*一次读取的大小<实际大小,则所有内容都要*/
if(actualSize > len) {
System.out.println(new String(flush, 0, len));
actualSize -= len;/*实际大小减少*/
}else {/*一次读取的大小>=实际大小,则只能要实际大小那么多的内容*/
System.out.println(new String(flush, 0, actualSize));
break;/*跳出循环*/
}
}
raf.close();/*需要释放*/
}
}
文件大小:78
分割文件块数:3
0-->0-->30
Whose life , if you look at it
1-->30-->30
under a microscope , doesn't
2-->60-->18
have any flaws.