Android 从隐式意图中获取 .txt 文件
Android Getting .txt files from implicit intents
我希望用户从设备中选择一些 .txt 文件,然后我的应用程序将其副本存储在其资产文件夹中。
buttonChooseFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent txtIntent = new Intent(Intent.ACTION_GET_CONTENT);
txtIntent.setType("text/plain");
startActivityForResult(txtIntent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
File file = new File(data.getData().getPath());
chosenTxtFile = file;
}
}
}
当我运行时,我确实可以从我的phone中选择一个文件,但是现在当我想执行下面的代码时,没有任何反应:
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(chosenTxtFile));
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
br.close();
}
catch (IOException e) {
}
textView.setText(stringBuilder.toString());
我在这里读到: 我应该使用 ContentResolver。但是,由于我是新手,所以我不确定如何。任何人都可以帮我编写适用于我的代码的 ContentResolver 吗?非常感谢!
I want the user to choose some .txt file from device and then my app to store the copy of it inside its assets folder.
首先,资产在运行时是 read-only。设备上没有"assets folder"。
其次,您的代码假定 ACTION_GET_CONTENT
returns 文件系统路径。多年来一直不是这种情况。
Could anyone please help me write ContentResolver that would work with my code?
第 1 步:停止考虑文件,因为 ACTION_GET_CONTENT
可以从许多地方获取内容,其中很少涉及文件系统上的文件
第 2 步:使用 Uri
(data.getData()
),而不仅仅是其中的一部分 (data.getData().getPath()
)
第 3 步:将 Uri
传递给 getContentResolver().openInputStream()
,并使用它和 InputStreamReader
而不是 FileReader
我希望用户从设备中选择一些 .txt 文件,然后我的应用程序将其副本存储在其资产文件夹中。
buttonChooseFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent txtIntent = new Intent(Intent.ACTION_GET_CONTENT);
txtIntent.setType("text/plain");
startActivityForResult(txtIntent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
File file = new File(data.getData().getPath());
chosenTxtFile = file;
}
}
}
当我运行时,我确实可以从我的phone中选择一个文件,但是现在当我想执行下面的代码时,没有任何反应:
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(chosenTxtFile));
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
br.close();
}
catch (IOException e) {
}
textView.setText(stringBuilder.toString());
我在这里读到:
I want the user to choose some .txt file from device and then my app to store the copy of it inside its assets folder.
首先,资产在运行时是 read-only。设备上没有"assets folder"。
其次,您的代码假定 ACTION_GET_CONTENT
returns 文件系统路径。多年来一直不是这种情况。
Could anyone please help me write ContentResolver that would work with my code?
第 1 步:停止考虑文件,因为 ACTION_GET_CONTENT
可以从许多地方获取内容,其中很少涉及文件系统上的文件
第 2 步:使用 Uri
(data.getData()
),而不仅仅是其中的一部分 (data.getData().getPath()
)
第 3 步:将 Uri
传递给 getContentResolver().openInputStream()
,并使用它和 InputStreamReader
而不是 FileReader