流程是:
.txt
个文件而是.doc
,我想在重写上面的第3步中将其转换为常规.txt
文件。以下是代码:
// 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?
}
答案 0 :(得分:6)
步骤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));
这是解决问题的最低要求。
但是,MIME类型*/*
将匹配任何类型的文件,而不仅仅是文本文件。不应使用readLine()
复制二进制文件。如果您只想要纯文本文件,请使用text/plain
代替*/*
。
答案 1 :(得分:2)
对于那些在此处难以解决该代码的人来说,是固定的
ab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICKFILE_RESULT_CODE) {
Uri uri = data.getData();
LaterFunction(uri);
}
}
public void LaterFunction(Uri uri) {
BufferedReader br;
FileOutputStream os;
try {
br = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri)));
//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());
Log.w("nlllllllllllll",line);
}
br.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}