Java黑皮书17章第10题

Java程序实现文件拆分
该博客介绍了一个Java程序,用于将大文件拆分为多个1KB的子文件。程序首先从用户输入获取文件路径,然后读取文件内容,将文件按1KB大小进行切分,并将每个子文件写入到指定的文件名加编号的文件中。程序还输出了原文件大小和每个子文件的路径及长度。这个方法对于大文件管理和传输非常有用。

 拆分文件的方法

import java.io.*;
import java.util.*;
public class Exercise17_10 {
	public static void main(String[] args) throws Exception{
		Scanner sc = new Scanner(System.in);
		ArrayList array = new ArrayList<>();
		System.out.print("输入文件路径:");
		String filename = sc.nextLine();//输入文件路径
		File file = new File(filename);
		split(file);                    //拆分方法
	}
	public static void split(File file){
		byte[] data = new byte[(int)file.length()];
		try{
			FileInputStream re = new FileInputStream(file);//读取
			re.read(data);
			re.close();
		}catch (FileNotFoundException ex){
			ex.printStackTrace();
		}catch (IOException ex){
			ex.printStackTrace();
		}
		System.out.println(data.length / 1024 + "k");//原文件大小
		int len = 1024;
		int n = (int)(file.length() / len);//拆分后子文件个数,大小均为1kb
		File[] file1 = new File[n + 1];
		for(int i=0;i<n + 1;i++){
			int start = i * 1024;
			int end = (i + 1) * 1024;
			file1[i] = new File(file + "." + (i+1));
			if(i<n){
				byte[] b = Arrays.copyOfRange(data, start, end);//复制到子文件
				try{
					FileOutputStream ou = new FileOutputStream(file1[i]);//写入
					ou.write(b);
					ou.close();
				}catch(FileNotFoundException ex){
					ex.printStackTrace();//输出报错位置
				}catch (IOException ex){
					ex.printStackTrace();
				}
			}else{
				start = i * 1024;
				end = (int)file.length();
				byte[] b = Arrays.copyOfRange(data, start, end);
				try{
					FileOutputStream ou = new FileOutputStream(file1[i]);
					ou.write(b);
					ou.close();
				}catch(FileNotFoundException ex){
					ex.printStackTrace();
				}catch(IOException ex){
					ex.printStackTrace();
				}
			}
			System.out.println("子文件夹:"+file1[i].getAbsolutePath()+ "长度:"+file1[i].length());
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值