gpt4 book ai didi

Android通过OTG数据线将文件写入USB

转载 作者:搜寻专家 更新时间:2023-11-01 07:55:12 24 4
gpt4 key购买 nike

我一直在搜索有关android 文件写入的许多主题,但大多数人都想将文件写入android 内部存储。其他想在外置SD卡上写文件的根本没有成功。我的情况非常相似,但我认为将文件写入外部 USB 是完全不同的情况。

我正在使用三星 galaxy Note II 运行原装 TouchWiz 4.4.2 [未 root]。我的手机支持微型 USB-OTG,我可以将我的 USB 安装为 rwxrwx--x 而无需生根。我的USB的完整路径是/storage/UsbDriveA。

我尝试使用 Environment.getExternalStorageDirectory() 获取路径或直接使用路径(如上所述),但都没有成功。第一个返回内部存储路径,第二个返回“权限被拒绝”的错误。我已经把

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在 Android Manifest 中,所以我想知道为什么我的代码不起作用。

此外,我可以使用 Root Browser(无需 root 即可使用它)和 Simple Browser 将任何内容写入我的 USB,因此我相信有办法做到这一点。

这是我的代码:

File file = new File(path.getAbsolutePath(), "test.txt");
// File file = new File("/storage/extSdCard","test.txt");
err = false;
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.print(get);
pw.flush();
pw.close();
f.close();
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "writing error",Toast.LENGTH_LONG).show();
err = true;
}
Log.i("File Path:", file.getPath());

最佳答案

从 android 4.4 开始,您可以使用存储访问框架来访问可移动媒体(参见 https://commonsware.com/blog/2014/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) 拦截返回 Intent

@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通过OTG数据线将文件写入USB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28760025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com