- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- [code]import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- public class FileCutter {
- private long len; // 文件总大小
- private long perLen; // 每一份文件的大小
- private long startPos; // 开始时索引
- private long endPos; // 结束索引
- /**
- * 切割文件
- *
- * @param srcFile
- * 源文件
- * @param desPath
- * 目标路径
- * @param num
- * 将文件分为几份
- * @throws IOException
- * @throws FileNotFoundException
- */
- public void cut(File srcFile, int num) throws FileNotFoundException,
- IOException {
- // 文件总大小
- len = srcFile.length();
- perLen = len / num;
- startPos = 0L;
- endPos = perLen;
- System.out.println(perLen + "------");
- // 将文件切割为num份,依次切割
- for (int i = 0; i < num; i++) {
- new Copyer(srcFile, startPos, endPos, "droid" + i).copy();
- startPos += perLen;
- if (i == (num - 2)) {
- endPos = len;
- } else {
- endPos += perLen;
- }
- System.out.println("start: " + startPos + " end: " + endPos + i);
- }
- }
- }
复制代码 public class Copyer {
private File srcFile; // 目标文件
private long startPos; // 开始索引
private long endPos; // 结束索引
private long hasCopyed; // 已经复制的文件的索引
private long len; // 文件总大小
private RandomAccessFile rIn;
private RandomAccessFile rOut;
private String desName; //各文件名称
public Copyer(File srcFile, long startPos, long endPos, String desName) {
this.srcFile = srcFile;
this.startPos = startPos;
this.endPos = endPos;
hasCopyed = startPos;
this.desName = desName;
}
public void copy() throws FileNotFoundException, IOException {
try {
// 只读
rIn = new RandomAccessFile(srcFile, "r");
// 只读写
rOut = new RandomAccessFile(desName, "rw");
len = srcFile.length();
rIn.seek(startPos);
rOut.seek(startPos);
int i = 0;
int sum = 0;
byte[] buff = new byte[1024 * 1024 * 24];
while (((i = rIn.read(buff)) != -1) && endPos <= len) {
if (hasCopyed + i > endPos) {
i = (int) (endPos - hasCopyed);
}
hasCopyed += i;
// startPos = hasCopyed;
rOut.write(buff, 0, i);
sum += i;
System.out.println("每次大小: " + sum);
}
// System.out.println("startPos: " + startPos + " endPos: " +
// endPos);
} finally {
if (rIn != null) {
rIn.close();
}
if (rOut != null) {
rOut.close();
}
}
}
}[/code]
|
|