在Intent之后读取的Android打开文本文件.ACTION_GET_CONTENT [英] Android open text file to read after Intent.ACTION_GET_CONTENT
本文介绍了在Intent之后读取的Android打开文本文件.ACTION_GET_CONTENT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
流为:
- 用户需要选择要使用的文本文件,然后弹出默认的Android资源管理器.
- 然后我要存储包含文件名的字符串,以实际打开文件进行读取.
- 我想打开该文件,然后将其重写为应用程序内部存储中的新文件.
- 我想从应用程序内部存储中打开新创建的文件.
- 奖金1-如果现在是
.txt
文件,但现在是.doc
,我想在上面重写的第3步中将他转换为常规的.txt
文件.
奖金2-如何处理大型文本文件?
- The user needs to select text file for use and the default Android explorer whatever pops up.
- Then I want to store string containing the file name, to actually open the file for reading.
- I want to open that file and rewrite him to new file on app internal storage.
- I want to open the new created file from app internal storage.
- Bonus 1 - If it's now
.txt
file but.doc
, I want to convert him to regular.txt
file in step 3 above of rewriting.
Bonus 2 - How to handle large text files?
代码如下:
// 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?
}
推荐答案
步骤1:删除String filePathName = "WHAT TODO ?";
步骤2:将LaterFunction(filePathName);
更改为LaterFunction(uri);
步骤3:将br = new BufferedReader(new FileReader("WHAT TODO ?"));
更改为br = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri));
这是解决您的问题的最低要求.
That is the minimum necessary to address your question.
但是,MIME类型*/*
将匹配任何类型的文件,而不仅仅是文本文件.二进制文件不应使用readLine()
复制.如果只需要纯文本文件,请使用text/plain
而不是*/*
.
However, a MIME type of */*
will match any type of file, not just text files. Binary files should not be copied using readLine()
. If you only want plain text files, use text/plain
instead of */*
.
这篇关于在Intent之后读取的Android打开文本文件.ACTION_GET_CONTENT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文