我希望用户从设备中选择一些.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;
}
}
}
当我运行它时,我确实可以从手机中选择一个文件,但现在当我想执行以下代码时,没有任何反应:
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());
我在这里阅读:Android: Reading txt file using implicit intent我应该使用ContentResolver。但是,由于我是新手,我不确定如何。有人可以帮我写一下可以使用我的代码的ContentResolver吗?非常感谢!
答案 0 :(得分:1)
我希望用户从设备中选择一些.txt文件,然后我的应用程序将其副本存储在其资源文件夹中。
首先,资产在运行时是只读的。没有"资产文件夹"在设备上。
其次,您的代码假定ACTION_GET_CONTENT
返回文件系统路径。多年来情况并非如此。
有人可以帮我写一下可以使用我的代码的ContentResolver吗?
步骤1:停止考虑文件,因为ACTION_GET_CONTENT
可以从许多地方获取内容,其中很少涉及文件系统上的文件
步骤2:使用Uri
(data.getData()
),而不只是一部分(data.getData().getPath()
)
第3步:将Uri
传递给getContentResolver().openInputStream()
,然后使用InputStreamReader
代替FileReader