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

被折叠的 条评论
为什么被折叠?



