Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Created March 29, 2019 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twiceyuan/da4196c6d079ff0bdd5949de6c693762 to your computer and use it in GitHub Desktop.
Save twiceyuan/da4196c6d079ff0bdd5949de6c693762 to your computer and use it in GitHub Desktop.
[Uri 获取 Byte 数组] #Android

很多上传操作需要文件对象或者 byte 数组,但是 Uri 获取文件对象是不方便的(content 类型的 Uri),但是相对于获取 InputStream 是方便的:

InputStream iStream = getContentResolver().openInputStream(uri);
byte[] inputData = getBytes(iStream);

然后 InputStream 获取目标文件的 bytes

public byte[] getBytes(InputStream inputStream) throws IOException {
  ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
  int bufferSize = 1024;
  byte[] buffer = new byte[bufferSize];

  int len = 0;
  while ((len = inputStream.read(buffer)) != -1) {
    byteBuffer.write(buffer, 0, len);
  }
  return byteBuffer.toByteArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment