2017-10-11 120 views
0

我正在嘗試讀取存儲在我的移動設備外部存儲器中的文本文件,但它引發此錯誤: - 讀取文本文件時發生錯誤!!/storage/emulated/0/atom .TXT:打開失敗:ENOENT(沒有這樣的文件或目錄) 下面的代碼在android中讀取文本文件

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button button = (Button) findViewById(R.id.btn_picker); 

    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      try { 
       fileOpener(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 

} 

private void fileOpener() throws IOException { 
    File sdcard = Environment.getExternalStorageDirectory(); 

    //Get the text file 
    File file = new File(sdcard,"atom.txt"); 
    //Read text from file 
    StringBuilder text = new StringBuilder(); 

    try { 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     String line; 

     while ((line = br.readLine()) != null) { 
      text.append(line); 
      text.append('\n'); 
     } 
    } 
    catch (IOException e) { 

     Log.e("Error", "Error occured while reading text file!!" + e.getMessage()); 
    } 

    //Find the view by its id 
    Log.d("Text",text.toString()); 
} 

}

我怎麼能想出解決辦法?
編輯:atom.txt文件已保存在我的設備,但仍然是拋出相同的錯誤。

+0

https://stackoverflow.com/a/23737335/1320704 – HomeIsWhereThePcIs

回答

0

該文件不存在,所以Environment.getExternalStorageDirectory返回的路徑不是您所期望的。根據API docs,此路徑不保證是SD卡。

+0

好吧,我知道你剛纔說的,但是你能否告訴我在上面的代碼中應該做些什麼修改才能正確運行。這對我有幫助。 – Logan