2017-10-11 115 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