从SD卡读取

时间:2013-03-06 21:11:13

标签: java android file-io android-sdcard

我正在尝试使用Java从我的SD卡读取一个简单的文本文件,我似乎无法打开它。我在Ubuntu 12.04上使用Eclipse for Mobile Developers。这是主要活动的onCreate()方法中的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String status = "Hello, is it me you're looking for?";
    String storageState = Environment.getExternalStorageState();

    File dir = Environment.getExternalStorageDirectory();
    File f = new File(dir, "textTest.txt");

    if (f.exists()) {
        status = "File is found!";
    } else {
        status = "File is not found!";
    }

    this.text1 = (TextView) findViewById(R.id.textView1);
    text1.setText(status.subSequence(0, status.length()));
}

此外,以下是我为File f尝试过的一些构造函数,它们都没有工作:

File f = new File(dir, "textTest.txt");
File f = new File("/sdcard/textTest.txt");
File f = new File(dir, "mnt/sdcard/textTest.txt");

最后,我使用上面的storageState字符串检查了外部存储状态,Environment.getExternalStorageState()返回的值为mounted。我唯一的领先是我认为可能与SD卡是否可读有关,但这只是猜测。有什么想法吗?

加了: 如果您没有猜到,我启动活动时TextView对象会显示“ File not found!”。

已添加2: 好吧,我刚试过一些有用的东西。当我通过USB连接手机时,与手机相关的两个文件夹打开:一个包含内部存储器中的所有文件夹(数据,DCIM等),我假设的文件夹连接到SD卡,因为我通过笔记本电脑读卡器添加了文件,然后将其输入手机。但是,当我将文件“testText.txt”复制到第一个文件夹(我假设它与内部存储有关)时,构造函数File f = new File("/sdcard/textTest.txt");可以工作。 Howcome?

1 个答案:

答案 0 :(得分:0)

基于评论..

将其添加到 AndroidManifest.xml

android.permission.READ_EXTERNAL_STORAGE

此外,如果您使用WRITE操作执行某些操作,请添加此权限

android.permission.WRITE_EXTERNAL_STORAGE