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

该代码示例展示了如何使用Java的InputStream和OutputStream实现文件的断点续传功能。程序首先从源文件读取数据,然后将数据写入目标文件,通过一个随机数决定在哪个位置停止写入,模拟断点情况。之后程序跳过已写入的目标文件部分,继续从断点处读取并写入剩余数据,完成续传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.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 block
			e.printStackTrace();
		} finally{
			try {
				fos.flush();
				fos.close();
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		try {
			fis = new FileInputStream(inFile);
			fis.skip(outFile.length());//跳过已读数据
			fos = new FileOutputStream(outFile,true);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			index = 0;
			while((inLength = fis.read(buf)) != -1){
				index++;//读到一个字节数组了
					fos.write(buf,0,inLength);
			}
				
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				fos.flush();
				fos.close();
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值