Johanna
Johanna

Reputation: 27628

Storing a large binary file

Are there any ways to store a large binary file like 50 MB in the ten files with 5 MB? thanks are there any special classes for doing this?

Upvotes: 0

Views: 674

Answers (2)

user85421
user85421

Reputation: 29680

Use a FileInputStream to read the file and a FileOutputStream to write it.
Here a simple (incomplete) example (missing error handling, writes 1K chunks)

  public static int split(File file, String name, int size) throws IOException {
    FileInputStream input = new FileInputStream(file);
    FileOutputStream output = null;
    byte[] buffer = new byte[1024];
    int count = 0;
    boolean done = false;
    while (!done) {
      output = new FileOutputStream(String.format(name, count));
      count += 1;
      for (int written = 0; written < size; ) {
        int len = input.read(buffer);
        if (len == -1) {
          done = true;
          break;
        }
        output.write(buffer, 0, len);
        written += len;
      }
      output.close();
    }
    input.close();
    return count;
  }

and called like

File input = new File("C:/data/in.gz");
String name = "C:/data/in.gz.part%02d";  // %02d will be replaced by segment number
split(input, name, 5000 * 1024));

Upvotes: 1

BalusC
BalusC

Reputation: 1108632

Yes, there are. Basically just count the bytes which you write to file and if it hits a certain limit, then stop writing, reset the counter and continue writing to another file using a certain filename pattern so that you can correlate the files with each other. You can do that in a loop. You can learn here how to write to files in Java and for the remnant just apply the primary school maths.

Upvotes: 0

Related Questions