0

I am developing an application which I capture videos in it. I am saving the recorded videos to the phone. What I want to do is to convert the saved files to byte arrays.

3
  • You want to read a File's contents into a byte[]? Commented Sep 7, 2012 at 14:29
  • 1
    Assuming the possibility of your videos being large, you may not want to convert the whole video file content to byte array as you may run out of memory. Commented Sep 7, 2012 at 14:32
  • Peter - yes, Rajesh - my videos are small (max 5mb) Commented Sep 7, 2012 at 14:39

2 Answers 2

1
    // Serialize to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeObject(yourObject);
    out.close();

    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();

    //write bytes to private storage on filesystem
    FileOutputStream fos = new FileOutPutStream("/....your path...");
    fos.write(buf);
    fos.close();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this code which may help you:

public static byte[] getBytesFromFile(File file) throws IOException {

InputStream is = new FileInputStream(file);
System.out.println("\nDEBUG: FileInputStream is " + file);

// Get the size of the file
long length = file.length();
System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

/*
 * You cannot create an array using a long type. It needs to be an int
 * type. Before converting to an int type, check to ensure that file is
 * not loarger than Integer.MAX_VALUE;
 */
if (length > Integer.MAX_VALUE) {
    System.out.println("File is too large to process");
    return null;
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while ((offset < bytes.length) && ((numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)) {
    offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
    throw new IOException("Could not completely read file " + file.getName());
}

is.close();
return bytes;}

2 Comments

You could've linked to the original article, downvoting for begging acceptance on someone elses code (I was about to post the exact same snippet really) with the article.
@Shark You seem to know where this code comes from? Perhaps you can add a link here so we can properly attribute it to the original author?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.