您可以使用skip(long)方法跳过InputStream中的字节数,也可以在File对象上创建RandomAccessFile并调用其seek(long)方法将指针设置为该位置,以便您可以从此处开始读取.
下面的快速测试将读取4mb文件(介于3m和4mb之间),并将读取的数据写入“ .out”文件.
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
long threeMb = 1024 * 1024 * 3;
File assembled = new File(args[0]); // your downloaded and assembled file
RandomAccessFile raf = new RandomAccessFile(assembled, "r"); // read
raf.seek(threeMb); // set the file pointer to 3mb
int bytesRead = 0;
int totalRead = 0;
int bytesToRead = 1024 * 1024; // 1MB (between 3M and 4M
File f = new File(args[0] + ".out");
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024 * 128]; // 128k buffer
while(totalRead < bytesToRead) { // go on reading while total bytes read is
// less than 1mb
bytesRead = raf.read(buffer);
totalRead += bytesRead;
out.write(buffer, 0, bytesRead);
System.out.println((totalRead / 1024));
}
}
}