Question

I know that there's a way of converting a file to byte array in chunks, here's a sample code:

 InputStream inputStream = new FileInputStream(videoFile);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     byte[] b = new byte[1024];
     int bytesRead =0;
     while ((bytesRead = inputStream.read(b)) != -1)
     {
       bos.write(b, 0, bytesRead);
     }

I'm looking for the opposite: a way of converting a byte array into a file in chunks. I didn't find any example of doing it in chunks.

Was it helpful?

Solution

You just have to use either the write(byte[]) or write(byte[],int,int) methods from the FileOutputStream class.

OTHER TIPS

byte[] to file:

 FileOutputStream fop = null; File file;
        try {
            file = new File(filePath);
            fop = new FileOutputStream(file, true);
            fop.write(chunk);
            fop.flush();
            fop.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

Try this for file to byte[]:

 InputStream is = new FileInputStream(file);
        int length = (int) file.length();           
        int take = 262144;//size of your chunk
        byte[] bytes = new byte[take];
                    int offset=0;
        int a = 0;
        do {
            a = is.read(bytes, 0, take);
            offset += a;
            //And you can add here each chunk created in to a list, etc, etc.
            //encode to base 64 this is extra :)
            String str = Base64.encodeToString(bytes, Base64.DEFAULT);

        } while (offset < length);=
        is.close();
        is=null;

Consider generalizing the problem.

This method copies data in chunks:

  public static <T extends OutputStream> T copy(InputStream in, T out)
      throws IOException {
    byte[] buffer = new byte[1024];
    for (int r = in.read(buffer); r != -1; r = in.read(buffer)) {
      out.write(buffer, 0, r);
    }
    return out;
  }

This can then be used in both reading to and from byte arrays:

try (InputStream in = new FileInputStream("original.txt");
    OutputStream out = new FileOutputStream("copy.txt")) {
  byte[] contents = copy(in, new ByteArrayOutputStream()).toByteArray();
  copy(new ByteArrayInputStream(contents), out);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top