Skip to content

Instantly share code, notes, and snippets.

@fankay
Created April 9, 2014 14:17
Show Gist options
  • Save fankay/10275667 to your computer and use it in GitHub Desktop.
Save fankay/10275667 to your computer and use it in GitHub Desktop.
利用RandomAccessFile类将一个文件分割为多个文件(图片)
//分割
public static void splitFile(String path,int count) {
try {
RandomAccessFile raf = new RandomAccessFile(path, "r");
//文件总大小
long length = raf.length();
//每份文件大小
long maxSize = length / count;
//最后一份文件大小
long lastSize = 0L;
if(length % count != 0) {
lastSize = length % count;
}
for (int i = 0; i < count; i++) {
RandomAccessFile temp = new RandomAccessFile("C:/temp-"+i+".jpg", "rw");
raf.seek(i * maxSize);
byte[] buffer ;
if(i == count-1) {
buffer = new byte[(int) (maxSize+lastSize)];
} else {
buffer = new byte[(int) maxSize];
}
int len = raf.read(buffer);
temp.write(buffer, 0, len);
temp.close();
}
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//合并
RandomAccessFile allFile = new RandomAccessFile("C:/new.jpg", "rw");
for (int i = 0; i <= 2; i++) {
RandomAccessFile raf = new RandomAccessFile("C:/temp-"+i+".jpg", "r");
byte[] buffer = new byte[1024];
int len = -1;
while((len = raf.read(buffer)) != -1) {
allFile.write(buffer,0,len);
}
raf.close();
}
allFile.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment