利用InputStream和OutputStream流完成文件的断点续传,(原理)

来源:互联网 发布:淘宝上误点了确认收货 编辑:程序博客网 时间:2024/06/03 22:37
package test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.util.Random;public class PrintTest {public static void main(String[] args) {// TODO Auto-generated method stub//文件断点续传File inFile = new File("D:\\test\\input.wmv");File outFile = new File("D:\\test\\output.wmv");System.out.println(inFile.length());FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream(inFile);fos = new FileOutputStream(outFile);} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}int inLength = 0;int index = 0;//用于记录读取的字节数组数//随机读取数组个数Random rd = new Random();int s = rd.nextInt(100);System.out.println("s = " + s);byte[] buf = new byte[1024];try {while((inLength = fis.read(buf)) != -1){index++;//读到一个字节数组了if (index <= s) {fos.write(buf,0,inLength);}else break;}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{try {fos.flush();fos.close();fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {fis = new FileInputStream(inFile);fis.skip(outFile.length());//跳过已读数据fos = new FileOutputStream(outFile,true);} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {index = 0;while((inLength = fis.read(buf)) != -1){index++;//读到一个字节数组了fos.write(buf,0,inLength);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{try {fos.flush();fos.close();fis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
0 0