将文件拆成多个小的分片文件,再将这些小文件合并恢复成原来的大文件,通常的方式就是使用FileOutputStream按照顺序append,如果采用多线程合并会导致文件错乱。java1.0的RandomAccessFile类把文件看成一个巨大的字节数组,seek方法能指定任意的数组位置,相当于一个游标,通过这个类的相关api能够实现分片文件的任意先后顺序合并
public static void main(String[] args) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(new File("C:\\Users\\jizhang\\Desktop\\test\\RandomAccessFileTest.txt"), "rw");
byte[] contentBytes = "设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。".getBytes();
int shardSize = 10;
int shardTotal = (contentBytes.length + shardSize - 1) / shardSize;
byte[][] tempData = new byte[shardTotal][shardSize];
for (int i = 0; i < shardTotal; i++) {
int begin = i * shardSize;
int end = Math.min((begin + shardSize), contentBytes.length);
tempData[i] = Arrays.copyOfRange(contentBytes, begin, end);
}
List<Integer> seqList = new ArrayList<>();
for (int i = 0; i < tempData.length; i++) {
seqList.add(i);
}
Collections.shuffle(seqList);
System.out.println("seqList = " + seqList);
for (Integer index : seqList) {
randomAccessFile.seek(index * shardSize);
randomAccessFile.write(tempData[index]);
}
}