断点续传小demo

╄→гoц情女王★ 提交于 2019-11-26 16:36:36
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 {

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!