Created
September 20, 2014 07:39
-
-
Save precious-ming/13570298fd0d59aeceb2 to your computer and use it in GitHub Desktop.
利用RandomAccessFile类将一个文件分割为多个文件(图片)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//分割 | |
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