Skip to content

Instantly share code, notes, and snippets.

@Logan676
Created January 22, 2016 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Logan676/04ce58e65bc9e696a057 to your computer and use it in GitHub Desktop.
Save Logan676/04ce58e65bc9e696a057 to your computer and use it in GitHub Desktop.
Read portions of bytes to byte array and store them in new files when buffer is full or it is end of file
class FileSplit {
public static void splitFile(File f) throws IOException {
int partCounter = 1;//I like to name parts from 001, 002, 003, ...
//you can change it to 0 if you want 000, 001, ...
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(f))) {//try-with-resources to ensure closing stream
String name = f.getName();
int tmp = 0;
while ((tmp = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
File newFile = new File(f.getParent(), name + "."
+ String.format("%03d", partCounter++));
try (FileOutputStream out = new FileOutputStream(newFile)) {
out.write(buffer, 0, tmp);//tmp is chunk size
}
}
}
}
public static void main(String[] args) throws IOException {
splitFile(new File("D:\\destination\\myFile.mp3"));
}
}
@Logan676
Copy link
Author

public static void mergeFiles(List<File> files, File into)
        throws IOException {
    try (BufferedOutputStream mergingStream = new BufferedOutputStream(
            new FileOutputStream(into))) {
        for (File f : files) {
            Files.copy(f.toPath(), mergingStream);
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment