[英]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.