简体   繁体   中英

Convert File object to byte array

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.

    // 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();

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;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM