2013-03-06 118 views
1

我想讀從我的SD卡使用Java簡單的文本文件,我似乎不能從閱讀中能打開它。我在Ubuntu 12.04上使用Eclipse for Mobile Developers。下面是在onCreate()方法主要活動的代碼:從SD卡

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對象讀取「找不到文件!」當我開始練習。

新增2: 好吧,我只是嘗試一些工作。當我通過USB連接手機,兩個文件夾與打開手機:一個擁有所有從內部存儲(數據,DCIM ...等),我假設連接到SD卡中的文件夾和文件夾的,因爲我通過筆記本電腦讀卡器添加了文件,然後將其輸入到手機中。然而,當我的文件「testText.txt」複製到第一個文件夾(我認爲是關係到內部存儲),File f = new File("/sdcard/textTest.txt");工作的構造。怎麼來的?

+2

做u有清單中的'write_external_storage'權限? – 2013-03-06 21:23:05

+0

不,但我不想寫入文件。我正在閱讀。而根據此鏈接:http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29,read_external_storage是未來的版本 – naxchange 2013-03-06 21:25:36

+0

如果你看logcat中,可能會向您發出警告如果你需要聲明任何需要的權限。 – 2013-03-06 21:26:46

回答

0

基於評論..

添加到您的AndroidManifest.xml

android.permission.READ_EXTERNAL_STORAGE 

此外,如果你不與寫操作出頭添加此權限

android.permission.WRITE_EXTERNAL_STORAGE 
+1

的'android.permission.READ_EXTERNAL_STORAGE'目前不強制執行時刻,最近又加入了** API ** ** 16 **。任何聲明「android.permission.WRITE_EXTERNAL_STORAGE」權限的應用程序都被隱式授予READ權限。 – kaderud 2013-03-06 22:57:41