最近遇到一個問題,某網盤上傳文件時,文件大小超過了4個G ,不能上傳,所以就想到了利用的java的IO流,將文件分割成多個小文件,上傳到網盤上,等到需要用的時候,下載下來然后再進行文件的合並就可以了。
這里以分割一個8.85M的PDF文件為例,分割成每個大小為1M的文件,分割文件的大小,只需修改size即可,代碼如下:
1.文件的分割
public static void main(String[] args) throws IOException {
//要分割出來的文件的大小
int size = 1024*1024*1;//1M
BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("D:\\zzy\\aaaa\\fileSplit\\java.pdf")));
int len = -1;
for (int i = 0; i < 9; i++) { //8.85M的文件分割成8個1M的,和一個0.85M的
File file = new File("D:\\zzy\\aaaa\\fileSplit\\" + i + "temp.temp");//分割的文件格式可以隨便設置,只要文件合並時名稱一致即可
FileOutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream out = new BufferedOutputStream(outputStream);
int count = 0;
byte[] bt = new byte[1024 * 1024];//每次讀取1M,數組大小不能太大,會內存溢出,通過目標文件大小size判斷一下
while ((len = in.read(bt)) != -1) {
out.write(bt, 0, len);
count += len;
if(count>=size) {
break;//每次讀取1M,然后寫入到文件中
}
}
out.flush();
out.close();
outputStream.close();
System.out.println("文件已完成:" + file.getName());
}
System.out.println("文件已完成分割====");
}
2.文件的合並
public static void main(String[] args) throws IOException {
//文件合並
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File("D:\\zzy\\aaaa\\fileSplit\\java(merge).pdf")));
for (int i = 0; i < 9; i++) { //9個文件合並成8.85M的文件
File file = new File("D:\\zzy\\aaaa\\fileSplit\\" + i + "temp.temp");
FileInputStream inputStream = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(inputStream);
int len = -1;
byte[] bt = new byte[1024 * 1024];//每次讀取1M,數組大小不能太大,會內存溢出
while ((len = in.read(bt)) != -1) {
out.write(bt, 0, len);
}
in.close();
inputStream.close();
out.flush();
System.out.println("文件已完成:" + file.getName());
}
System.out.println("文件已完成合並====");
}
