[英]Reading from SD card
我正在尝试使用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
,但它们都不起作用:
File f = new File(dir, "textTest.txt");
File f = new File("/sdcard/textTest.txt");
File f = new File(dir, "mnt/sdcard/textTest.txt");
最后,我使用上面的storageState
字符串检查了外部存储状态,并mounted
了Environment.getExternalStorageState()
返回的值。 我唯一的线索是,我认为SD卡是否可读可能与它有关,但这只是一个猜测。 有任何想法吗?
补充:如果您没有猜到,当我启动活动时, TextView
对象将显示“ File not found! ”。
补充2:好的,我只是尝试了一些有效的方法。 当我通过USB连接手机时,会打开两个与手机相关的文件夹:一个文件夹具有内部存储器中的所有文件夹(数据,DCIM等),而我认为该文件夹已连接至SD卡,因为我通过笔记本电脑读卡器添加了文件,然后将其输入到手机中。 但是,当我将文件“ testText.txt”复制到第一个文件夹(我认为与内部存储有关)时,构造函数File f = new File("/sdcard/textTest.txt");
作品。 怎么会?
根据评论..
将此添加到您的AndroidManifest.xml
android.permission.READ_EXTERNAL_STORAGE
另外,如果您使用WRITE操作执行操作,请添加此权限
android.permission.WRITE_EXTERNAL_STORAGE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.