拆分
package com.work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class Test1 {
public static void main(String[] args) {
File f = new File("/home/roo/桌面/chai/面向对象.pdf");
split(f);
}
public static void split(File f) {
byte[] data = new byte[(int) f.length()];
try {
FileInputStream fis = new FileInputStream(f);
fis.read(data);// 读取文件到data中
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(data.length / 1024 + "k");
int len = 1024 * 100;
// 拆分为100k的文件夹
int n = (int) (f.length() / len);
// 剩下的不足100k的放另一个
int m = (int) (f.length() / len);
// 文件数组,用来存放文件。长度为总共需要生成文件的个数。
File[] fs = new File[n + 1];
for (int i = 0; i < n + 1; i++) {
int start = i * 102400;
int end = (i + 1) * 102400;
fs[i] = new File(f + "-" + i);
if (i < n) {
byte[] b = Arrays.copyOfRange(data, start, end);
try {
FileOutputStream fos = new FileOutputStream(fs[i]);
fos.write(b);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
start = i * 102400;
end = (int) f.length();
byte[] b = Arrays.copyOfRange(data, start, end);
try {
FileOutputStream fos = new FileOutputStream(fs[i]);
fos.write(b);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("子文件夹:" + fs[i].getAbsolutePath()
+ " 大小: " + fs[i].length());
}
}
}
合并
package com.work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class Test2 {
public static void main(String[] args) throws IOException {
File f1 = new File("/home/roo/桌面/z1/o");
File [] ff= f1.listFiles();
File f2 = new File("/home/roo/桌面/z2/p");
com(ff,f2);
}
public static void com(File[] fs,File newFile) {
int len = 0;
for (File file : fs) {
len += file.length();
}
//数组放合并的内容
byte[] b = new byte[len];
int len1 = 0;
for (File file : fs) {
byte[] bi = new byte[(int) file.length()];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(bi);
fis.close();
System.out.println(bi.length);
} catch (IOException e) {
e.printStackTrace();
}
System.arraycopy(bi, 0, b, len1, (int) file.length());
len1 +=file.length();
try {
FileOutputStream fos = new FileOutputStream(newFile);
fos.write(b);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}