package io03;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
- 随机读取和写入流 RandomAccessFile
- @author
*/
public class TestRandom {
public static void main(String[] args) throws IOException {
File src = new File("TestIFileCopy.java");
//总长度
long len = src.length();
//每块大小
int blockLength = 1024;
//块数:多少块
int size = (int)Math.ceil(len*1.0/blockLength);
//起始位置 实际大小
int begin = 0;
int actualSize = (int) (blockLength>len?len:blockLength);
for(int i = 0; i<size; i++) {
begin = i*blockLength;
if(i == size-1) {//最后一块
actualSize = (int) len;
}else {
actualSize = blockLength;
len -= actualSize;//剩余量
}
System.out.println(i+"-->"+begin+"-->"+actualSize);
test2(i, begin, actualSize);
}
}
//分块思想:起始 实际大小
/**
* 指定第i块的起始位置和实际长度
* @param i
* @param begin
* @param actualSize
* @throws IOException
*/
public static void test2(int i,int begin,int actualSize) throws IOException {
RandomAccessFile raf = new RandomAccessFile(new File("TestIFileCopy.java"), "r");
//起始位置
// int begin = 2;
//实际大小
int size= actualSize;
//随机读取
raf.seek(begin);
//读取
byte[] temp = new byte[1024];
int len = -1;
while((len = raf.read(temp)) != -1) {
if(size > len) {
//获取本次读取的所有内容
System.out.println(new String(temp,0,len));
size -= len;
}else {
System.out.println(new String(temp,0,size));
break;
}
}
}
//指定起始位置 读取剩余所有内容
public static void test1() throws IOException {
RandomAccessFile raf = new RandomAccessFile(new File("1.txt"), "r");
//随机读取
raf.seek(2);
//读取
byte[] temp = new byte[1024];
int len = -1;
while((len = raf.read(temp)) != -1) {
System.out.println(new String(temp,0,len));
}
raf.close();
}
}