nar*_*arb 2 android storage-access-framework
我是 SAF 的初学者。我想要做的是保存配置超级简单。假设文件是 .conf。
我将 .conf 复制到 conf.txt 并将其保存在 Drive 上。
这是我的代码:
tools.deleteFile(dst); // delete conf.txt if it exists
int res = tools.copyFile(src,dst); // copy .conf to conf.txt
if(res == -1) return;
tools.viewFile(dst);
// verify in Log info that the content of cnf.txt is correct
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, dst);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
我在云端硬盘中保存。该文件出现在我的电脑上,但当我打开它时,它是空的。
当我做相反的事情时:ACTION_OPEN_DOCUMENT
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
Uri uri;
if (resultCode == Activity.RESULT_OK){
if (requestCode == 30){
if (resultData != null) {
uri = resultData.getData();
try {
String content =
readFile(uri);
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
函数 readFile 打开文件并在读取时停止,因为没有数据。
我做错了什么?
该Intent(Intent.ACTION_CREATE_DOCUMENT)是CREATING文本文件,并使用onActivityResult()获得uri (location)的文件,那么你使用OutputStream到写数据(byte[])的文件。
private void createAndSaveFile() {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, "testFileSam.txt");
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
OutputStream outputStream = getContentResolver().openOutputStream(uri);
outputStream.write("Hi, welcome to Sam's Android classroom! Have a good day!".getBytes());
outputStream.close();
Toast.makeText(this, "Write file successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Fail to write file", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "File not saved", Toast.LENGTH_SHORT).show();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1762 次 |
| 最近记录: |