将File对象转换为字节数组

时间:2012-09-07 14:27:46

标签: java android

我正在开发一个应用程序,我在其中捕获视频。我将录制的视频保存到手机中。我想要做的是将保存的文件转换为字节数组。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

您可以使用以下代码:

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