Skip to content

Instantly share code, notes, and snippets.

@rezaiyan
Created November 14, 2020 14:07
Show Gist options
  • Save rezaiyan/ba1dab31a5260abffe511f518dce30d1 to your computer and use it in GitHub Desktop.
Save rezaiyan/ba1dab31a5260abffe511f518dce30d1 to your computer and use it in GitHub Desktop.
public class MultipartHelper {
private final String fileDir;
private final String outputDir;
public MultipartHelper(String fileDir, String outputDir) {
this.fileDir = fileDir;
String baseDir = BaseApplication.getAppContext().getObbDir() + File.separator + "uploads";
this.outputDir = baseDir + File.separator;
File upload = new File(baseDir);
if (!upload.exists()) {
upload.mkdir();
}
}
public void split() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(fileDir, "r");
try {
long sourceSize = 0;
sourceSize = raf.length();
long numSplits = sourceSize / (1024 * 100);
numSplits += sourceSize % (1024 * 100) > 0 ? 1 : 0;
long bytesPerSplit = sourceSize / numSplits;
long remainingBytes = sourceSize % numSplits;
for (int destIx = 1; destIx <= numSplits; destIx++) {
FileOutputStream outputStream = new FileOutputStream(new File(outputDir + "." + destIx));
BufferedOutputStream bw = new BufferedOutputStream(outputStream);
byte[] buf = new byte[(int) bytesPerSplit];
int val = raf.read(buf);
if (val != -1) {
bw.write(buf);
}
bw.close();
}
if (remainingBytes > 0) {
BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(new File(outputDir + "." + (numSplits + 1))));
readWrite(raf, bw, remainingBytes);
bw.close();
}
raf.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
raf.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public File[] getFiles() {
return new File(outputDir).listFiles();
}
public void close() {
FileUtils.deleteDir(new File(outputDir));
}
static void readWrite(RandomAccessFile raf, BufferedOutputStream bw, long numBytes) throws IOException {
byte[] buf = new byte[(int) numBytes];
int val = raf.read(buf);
if (val != -1) {
bw.write(buf);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment