找到一个大于100k的文件,按照100k为单位,拆分成多个子文件,并且以编号作为文件名结束。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class TestStream {
public static void main(String[] args) {
int eachSize = 100 * 1024;//100字节
File f = new File("E:/eclipse/eclipse.exe");
splitFile(f, eachSize);
}
//拆分的思路,先把源文件的所有内容读取到内存中,然后从内存中挨个分到子文件里
public static void splitFile(File f, int eachSize){
if (f.length() == 0){
throw new RuntimeException("文件长度等于0,不可拆分");//如果文件长度为0,则抛出一个运行时异常
}
byte fileCount[] = new byte[(int)f.length()];
try{//先将文件读入到数组中
FileInputStream fs = new FileInputStream(f);
fs.read(fileCount);
fs.close();
}catch(IOException e){
e.printStackTrace();
}
int fileNumber;//计算需要被拆分为多少子文件
if (fileCount.length % eachSize == 0){
fileNumber = (int)fileCount.length / eachSize;
}
else{
fileNumber = (int)fileCount.length / eachSize + 1;
}
for (int i = 0; i < fileCount.length; i++) {
String eachFileName = f.getName() + "-" + i;
File eachFile = new File(f.getParent(), eachFileName);
byte eachContent[];
// 从源文件的内容里,复制部分数据到子文件
// 除开最后一个文件,其他文件大小都是100k
// 最后一个文件的大小是剩余的
if (fileNumber - 1 != i){// 不是最后一个
eachContent = Arrays.copyOfRange(fileCount, i * eachSize, (i + 1) * eachSize);
}
else{// 最后一个
eachContent = Arrays.copyOfRange(fileCount, i * eachSize, fileCount.length);
}
try{ // 写出去
FileOutputStream fs2 = new FileOutputStream(eachFile);
fs2.write(eachContent);
fs2.close();
System.out.printf("输出子文件%s,其大小是%d字节%n", eachFile.getAbsoluteFile(), eachFile.length());
}catch(IOException e){
e.printStackTrace();
}
}
}
}