我有活动"听"打开文本文件,这意味着在清单中:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
所以我导航到文件浏览器,找到一些文本文件并尝试打开它,正如预期的那样,此活动存在于可用应用程序列表中以完成操作。当活动启动时,我知道Activity获得了正确的文件名,但它将文件视为空(不将内容打印到日志中)。
备注:该文件不为空,其他应用可以读取他,文件路径不包含空格,没有例外或崩溃。
我在这里做错了什么?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
//Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type != null && "text/plain".equals(type)) {
handleViewText(intent); //Handle text being sent
}
}
private void handleViewText(Intent intent) {
Uri uri = intent.getData();
//uri.getPath().toString(): /storage/emulated/0/dir/subDir/fileName.txt
BufferedReader br = null;
try {
String sCurrentLine;
InputStream is = getContentResolver().openInputStream(uri);
br = new BufferedReader(new InputStreamReader(is));
//This is also not working: br = new BufferedReader(new FileReader(uri.getPath()));
while ((sCurrentLine = br.readLine()) != null) {
Log.e("TAG", sCurrentLine); //never enters here
}
} catch (Exception e) {
//nothing
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {
//nothing
}
}
}
答案 0 :(得分:1)
试试这段代码:
public String read(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}