我希望用户从设备中选择一些.txt文件,然后我的应用程序将其副本存储在其assets文件夹中。
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吗?非常感激!
我希望用户从设备中选择一些.txt文件,然后我的应用程序将其副本存储在其assets文件夹中。
首先,资产在运行时是只读的。设备上没有“资产文件夹”。
其次,您的代码假定ACTION_GET_CONTENT
返回文件系统路径。多年来情况并非如此。
有人可以帮我写一下可以使用我的代码的ContentResolver吗?
步骤1:停止考虑文件,因为ACTION_GET_CONTENT
可以从许多地方获取内容,其中很少涉及文件系统上的文件
步骤#2:使用Uri
(data.getData()
),而不仅仅是它的一部分(data.getData().getPath()
)
步骤#3:将Uri
传递给getContentResolver().openInputStream()
,并使用它和InputStreamReader
而不是FileReader