我试图从Android Uri到字节数组.
我有以下代码,但它一直告诉我字节数组长61个字节,即使文件非常大 - 所以我认为它可能将Uri 字符串转换为字节数组,而不是文件:(
Log.d(LOG_TAG, "fileUriString = " + fileUriString);
Uri tempuri = Uri.parse(fileUriString);
InputStream is = cR.openInputStream(tempuri);
String str=is.toString();
byte[] b3=str.getBytes();
Log.d(LOG_TAG, "len of data is " + imageByteArray.length
+ " bytes");
Run Code Online (Sandbox Code Playgroud)
请有人帮我弄清楚该怎么办?
输出为"fileUriString = content:// media/external/video/media/53","len of data为61字节".
谢谢!
bra*_*ter 68
is.toString() 将为您提供InputStream实例的String表示形式,而不是其内容.
您需要将InputStream中的()字节读入数组.有两种读取方法可以做到这一点,read()一次读取一个字节,read(byte [] bytes)读取从InputStream到你传递给它的字节数组中的字节.
更新:要读取InputStream没有长度的字节,您需要读取字节,直到没有任何内容为止.我建议为自己创建一个这样的方法,这是一个很好的简单起点(至少我会用Java做这个).
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
小智 10
使用Apache Commons,您可以阅读所有字节,Stream感谢IOUtils.toByteArray(InputStream)下一个:
byte[] recordData = IOUtils.toByteArray(inStream);
Run Code Online (Sandbox Code Playgroud)
下载jar:http: //commons.apache.org/io/download_io.cgi
科特林方式:
@Throws(IOException::class)
private fun readBytes(context: Context, uri: Uri): ByteArray? =
context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
Run Code Online (Sandbox Code Playgroud)
在科特林,他们增加了便捷的扩展功能InputStream一样buffered,use和readBytes。
buffered 将输入流装饰为 BufferedInputStreamuse 处理关闭流readBytes 主要工作是读取流并写入字节数组错误案例:
IOException 可能在此过程中发生(如在 Java 中)openInputStream可以返回null。如果您在 Java 中调用该方法,您可以轻松地监督这一点。想想你想如何处理这个案例。| 归档时间: |
|
| 查看次数: |
54105 次 |
| 最近记录: |