javaseek原理的简单介绍

博主:adminadmin 2022-11-25 20:07:06 67

今天给各位分享javaseek原理的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java io seek()

seek是从文件开头开始计算跳过的长度,skip是从当前指针所指向的位置开始计算的

比如文件内容为“12345”当前指向3

seek(2);则指向2

skip(2);则指向5

看过api后猜得~~

ps:我在1.5的api中只找到skipBytes(int n) 这个方法,没有skip()

java中file.seek(0);是什么意思?

楼主 我要告诉你 file.seek(int类型的参数)表示从文件的第几个位置开始收索

这个程序中如果没有了file.seek(0);就会出错:

--------------- file.seek(0);专门用于随机读取流。所以在随机读取流的时候必须写

而且改变seek()中的数字也会出错:

--------只要你文件足够大 参数可以是一个任意整数

---------你出错是因为file.seek(0);是从位置0开始的 下面的那个语句:(System.out.println(file.readInt());)也是从第零个位置开始的

如果你要 file.seek(1); 去掉System.out.println(file.readInt());就可以了!

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

    }

}

javaseek原理的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、javaseek原理的信息别忘了在本站进行查找喔。

The End

发布于:2022-11-25,除非注明,否则均为首码项目网原创文章,转载请注明出处。