2015-10-31 37 views
0

我有「聽」來打開文本文件的活動,這意味着清單:Android的閱讀活動的文本文件,濾波器打開文本文件

<intent-filter> 
    <action android:name="android.intent.action.VIEW" /> 
    <category android:name="android.intent.category.DEFAULT" /> 
    <data android:mimeType="text/*" /> 
</intent-filter> 

所以我瀏覽到文件瀏覽器,找到一些文本文件,嘗試打開它,並按預期方式將此活動存在於可用應用程序的列表中以完成操作。當活動啓動時,我知道活動獲得了正確的文件名,但它將文件視爲空(不會將內容打印到日誌中)。

備註:該文件不是空的,其他應用可以讀取他,文件路徑不包含空格,沒有例外或崩潰。

我在做什麼錯在這裏?

@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

第一件事第一,加上'e.printStackTrace()'到catch塊,檢查是否有異常是拋出。 – Blackbelt

+0

@Blackbelt正如我在問題中提到的那樣,它沒有異常拋出它的測試,並且異常處理代碼被省略以僅用相關代碼的可讀問題。 – michael

回答

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; 

    } 
+0

謝謝,但它不起作用。 'uri'到字符串是'/ storage/emulated/0/dir/subDir/fileName.txt',所以我也從你的答案中省略了'.txt'的後綴,但它仍然不起作用。函數返回空字符串,但不打印StackTrace。 – michael

+0

好的...因爲你必須找到文件的絕對路徑。 –

+0

你是什麼意思?這不是路徑? – michael