2016-09-20 45 views
0

我通過pc中的filebrowser在我的android手機sdcard中創建文本文件。然後我嘗試在android應用中閱讀它。我得到了FileNotFoundException - no such path or directory exist錯誤。FileNotFoundException嘗試從SDCard中讀取

這是我的代碼

private String readFromFile(Context context) { 

     StringBuilder text = new StringBuilder(); 
     String state = Environment.getExternalStorageState(); 

     if (Environment.MEDIA_MOUNTED.equals(state)) { 
      File sdcard = Environment.getExternalStorageDirectory(); 
      File file = new File(sdcard,"sample.txt"); 
      //Read text from file 
      try { 
       //File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sample.txt"); 
       BufferedReader br = new BufferedReader(new FileReader(file));//Error occurs here 
       String line; 
       Toast.makeText(context, "success!", Toast.LENGTH_LONG).show(); 
       while ((line = br.readLine()) != null) { 
        text.append(line); 
        text.append('\n'); 
       } 
       br.close(); 
      } 
      catch (IOException e) { 
       e.getMessage(); 
       Toast.makeText(context, "Error!", Toast.LENGTH_LONG).show(); 
       //You'll need to add proper error handling here 
      } 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
// We can only read the media 
     } else { 
// Something else is wrong. It may be one of many other states, but all we need 
// to know is we can neither read nor write 
     }  
     return text.toString(); 
    } 

sample.txt存在於SD卡的根目錄(我已經三重檢查)。它有一些文字。

我在清單文件中給出了讀取外部存儲權限。

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.bulsy.graphapp"> 
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

我試圖運行應用程序斷開形式的PC,然後也沒有奏效示值誤差。可能是一個簡單的問題。任何人都可以解釋我哪裏出錯了嗎?

+2

請再次檢查您的interal存儲,而不是您的輔助存儲(sd卡)sample.txt是否可用。 –

+0

它必須是在SD卡權利?而我調試BufferedReader試圖讀取'/ storage/sdcard0/sample.txt'產生'Filenotfound'異常 –

回答

1

試試看。在日誌中打印以下內容並告訴我們路徑是什麼:sdcard.getPath()

此外,使用像ES文件資源管理器的應用程序來查看你的sample.txt文件的屬性,並獲得完整的路徑。他們匹配嗎?

如果路徑匹配,更換此:

File file = new File(sdcard,"sample.txt"); 

有了這個:

File file = new File("full_path_of_the_file"); 

這將幫助ü消除問題的癥結所在。
祝你好運。

+0

路徑是'/storage/sdcard0/sample.txt' –

+0

請嘗試以下操作。用'getExternalStorageDirectory(null)'替換'getExternalStorageDirectory()'。看看是否有所作爲 –

+0

路徑是不同的! ES瀏覽器說它是'/ storage/sdcard1/sample.txt'!它的工作!當我改變它,如你所說!乾杯! –

相關問題