java seek_java中seek()的用法
展開全部
寫段代碼你看一下吧,用于從文件指定的位置開始讀取,e69da5e887aa62616964757a686964616f31333332616363一般的下載工具都有斷點續傳功能,比如讀取某個文件讀取了一半,取消下載了,下次再下載的時候,從斷點的位置繼續下載,而不是重新下載文件,使用這個方法可以做到public class Test2 {
public static void main(String[] args) throws Exception {
String filepath = "E:/test.exe";
String outFile = "E:/copy.exe";
long pos = firstRead(filepath, outFile);
continueRead(filepath, outFile, pos);
}
/**
* 第一次只讀取文件的一半,到目標文件
*/
public static long firstRead(String filepath, String out) throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "r");
long fileLen = file.length();
FileOutputStream outStream = new FileOutputStream(out);
int sum = 0;? // 用于記錄當前讀取源文件的長度
byte[] cache = new byte[1024];
int len = -1;
while ((len = file.read(cache)) != -1 && sum < fileLen/2) {
outStream.write(cache, 0, len);
sum += len;
}
outStream.close();
file.close();
return sum;?? // 返回當前讀取源文件的長度
}
/**
* 從源文件指定位置繼續讀取文件內容,并輸出到目標文件
*/
public static void continueRead(String filepath, String out, long pos) throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "r");
file.seek(pos);
// 追加到目標文件中
FileOutputStream outStream = new FileOutputStream(out, true);
byte[] cache = new byte[1024];
int len = -1;
while ((len = file.read(cache)) != -1) {
outStream.write(cache, 0, len);
}
outStream.close();
file.close();
}
}
總結
以上是生活随笔為你收集整理的java seek_java中seek()的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬取微博评论数据的githu
- 下一篇: 扇贝计算机英语单词,扇贝单词英语版(co