我正在开发一个应用程序,我在其中捕获视频。我正在将录制的视频保存到手机中。我想要做的是将保存的文件转换为字节数组。
问问题
3484 次
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();
于 2012-09-07T14:39:23.543 回答
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;}
于 2012-09-07T15:08:04.617 回答