失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android 9 otg文件格式 Android通过OTG线将文件写入USB

android 9 otg文件格式 Android通过OTG线将文件写入USB

时间:2019-08-09 13:39:07

相关推荐

android 9 otg文件格式 Android通过OTG线将文件写入USB

从android 4.4开始,您可以使用Storage Access Framework访问可移动媒体(请参阅

/blog//04/09/storage-situation-removable-storage.html).

例如,我尝试将pdf文件从本地内存复制到由OTG适配器连接的可移动内存.唯一的限制:用户必须选择目标文件夹.

1)调用Intent.ACTION_CREATE_DOCUMENT:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

intent.setType("application/pdf");

intent.putExtra(Intent.EXTRA_TITLE, file.getName());

startActivityForResult(intent, REQUEST_CODE);

2)拦截返回意图

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data){

if(requestCode == REQUEST_CODE) {

if (resultCode != RESULT_OK) return;

copyFile(fileToCopy, data.getData());

}

}

3)使用ContentResolver打开outputStream并使用它来复制文件

private void copyFile(File src, Uri destUri) {

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

try {

bis = new BufferedInputStream(new FileInputStream(src));

bos = new BufferedOutputStream(getContentResolver().openOutputStream(destUri));

byte[] buf = new byte[1024];

bis.read(buf);

do {

bos.write(buf);

} while(bis.read(buf) != -1);

} catch (NullPointerException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (bis != null) bis.close();

if (bos != null) bos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

如果觉得《android 9 otg文件格式 Android通过OTG线将文件写入USB》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。