Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jan 22, 2016

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
You can’t perform that action at this time.