【发布时间】:2015-05-01 12:06:55
【问题描述】:
流程是:
- 用户需要选择要使用的文本文件和弹出的默认 Android 资源管理器。
- 然后我想存储包含文件名的字符串,以实际打开文件进行读取。
- 我想打开该文件并将他重写为应用内部存储上的新文件。
- 我想从应用内部存储打开新创建的文件。
- 奖励 1 - 如果现在是
.txt文件但.doc,我想在上面的重写步骤 3 中将他转换为常规.txt文件。
Bonus 2 - 如何处理大文本文件?
代码如下:
// 1. Start with user action pressing on button to select file
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
// 2. Come back here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICKFILE_RESULT_CODE) {
// Get the Uri of the selected file
Uri uri = data.getData();
String filePathName = "WHAT TODO ?";
LaterFunction(filePathName);
}
}
// 3. Later here
public void LaterFunction(String filePathName) {
BufferedReader br;
FileOutputStream os;
try {
br = new BufferedReader(new FileReader("WHAT TODO ?"));
//WHAT TODO ? Is this creates new file with
//the name NewFileName on internal app storage?
os = openFileOutput("newFileName", Context.MODE_PRIVATE);
String line = null;
while ((line = br.readLine()) != null) {
os.write(line.getBytes());
}
br.close();
os.close();
lastFunction("newFileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 4. And in the end here
public void lastFunction(String newFileName) {
//WHAT TODO? How to read line line the file
//now from internal app storage?
}
【问题讨论】:
-
“那么我想存储包含文件名的字符串”——这是不切实际的。首先,there is not necessarily a file that you can read。其次,您以后无需具备阅读
Uri的内容的能力。借助 Android 4.4+ 上的存储访问框架,如果存储提供程序允许,您可以获取持久权限并对Uri的内容进行长期读取访问。在此之前,您需要立即使用内容,而不是稍后。 -
除此之外,Stack Overflow 是针对编程问题的。你有什么问题?
-
1.假设稍后是同一“运行”上的其他功能。基本上我想把这个文件复制到我的内部存储中以供以后使用......
-
2.插入什么而不是“WHAT TODO?”
标签: android file storage internal