加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

断点续传小demo

发布时间:2020-12-15 05:25:01 所属栏目:Java 来源:网络整理
导读:package duandianxuchuan; import java.io.* ; public class Duandianxuchaun1 { private static int position = -1 ; public static void main(String[] args) { // 源文件和目标文件 File sourceFile = new File("D:/","test.txt" ); File targetFile = ne
package duandianxuchuan;

import java.io.*;

public class Duandianxuchaun1 {
    private static int position = -1;
    public static void main(String[] args) {
        //源文件和目标文件
        File sourceFile = new File("D:/","test.txt");
        File targetFile = new File("E:/","test.txt");
        //创建流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        byte[] buf = new byte[1];

        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(targetFile);
            while(fis.read(buf)!=-1) {
                fos.write(buf);
                //当读取3个的时候模拟出错
                if(targetFile.length() == 3){

                    position = 3;
                    throw new FileAccessException();
                }
            }
        } catch (FileAccessException e) {
            keepGoing(sourceFile,targetFile,position);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {

        }finally {

            try {
                // 关闭输入输出流
                if (fis != null)
                    fis.close();

                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }

    private static  void keepGoing(File sourceFile,File targetFile,int position){
        try {
            //设置延迟只是为了方便查看文件是否部分传输了
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try{
            RandomAccessFile readFile = new RandomAccessFile(sourceFile,"rw");
            RandomAccessFile writeFile = new RandomAccessFile(targetFile,"rw");
            readFile.seek(position);
            writeFile.seek(position);
            // 数据缓冲区
            byte[] buf = new byte[1];
            // 数据读写
            while (readFile.read(buf) != -1) {
                writeFile.write(buf);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
class FileAccessException extends Exception {

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读