java中seek()的用法

如题所述

写段代码你看一下吧,用于从文件指定的位置开始读取,一般的下载工具都有断点续传功能,比如读取某个文件读取了一半,取消下载了,下次再下载的时候,从断点的位置继续下载,而不是重新下载文件,使用这个方法可以做到

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();
    }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-30
seek是从文件开头开始计算跳过的长度,skip是从当前指针所指向的位置开始计算的
比如文件内容为“12345”当前指向3
seek(2);则指向2
skip(2);则指向5

看过api后猜得~~
ps:我在1.5的api中只找到skipBytes(int n) 这个方法,没有skip()
第2个回答  2013-05-08
io中的吧,设置开始读取位置
第3个回答  2013-05-08
不同的类有不同的seek()方法。

用法都差不多,读取流文件。
第4个回答  2013-08-23
java.io.RandomAccessFile //
javax.imageio.stream.FileImageOutputStream //
javax.imageio.stream.FileCacheImageOutputStream //
javax.imageio.stream.ImageInputStreamImpl //
and so on ............本回答被网友采纳
相似回答