2011-07-18 76 views
1

可能重複:
reading a specific file from sdcard in android如何讀取SD卡中的CSV文件或指定路徑的Android

我試圖做一個簡單的Android應用程序,基本上導入一個CSV並將其插入到我的數據庫表中。到目前爲止,我能夠讀取res文件夾中的csv文件。

我的示例csv文件名爲「test.csv」,基本上通過「InputStream is = this.getResources()。openRawResource(R.drawable.test);」來訪問。

這裏是我的示例代碼:

InputStream is = this.getResources().openRawResource 
      (R.drawable.test); 
       BufferedReader reader = new BufferedReader(new InputStreamReader 
      (is)); 
       try { 
        String line; 
        String brand = ""; 
        String model = ""; 
        String type = ""; 

        this.dh = new DataHelper(this); 
        //this.dh.deleteAllCar(); 
        while ((line = reader.readLine()) != null) { 
         // do something with "line" 

         String[] RowData = line.split(","); 
         brand = RowData[1]; 
         model = RowData[2]; 
         type = RowData[3]; 
         this.dh = new DataHelper(this); 
         //this.dh.deleteAllCar(); 
         this.dh.insertcsv(brand, model, type); 
        } 
       }catch (IOException ex) { 
        // handle exception 
       }finally { 
        try { 
         is.close(); 
        } 
        catch (IOException e) { 
         // handle exception 
        } 
       } 

這工作正常不過,我希望能夠做出特色,其中用戶可以指定在哪裏得到的文件(從手機的SD卡,等等等等)。但現在,我想知道如何從sdcard(mnt/sdcard/test.csv)訪問csv。

幫助將不勝感激!感謝和愉快的編碼!

回答

1

這裏是如何到SD卡的代碼,你應該能夠使用上面的代碼,以找出讀取部分:

private void writeToSDCard() { 
try { 
    File root = Environment.getExternalStorageDirectory(); 

    if (root.canWrite()){ 
     InputStream from = myContext.getResources().openRawResource(rID); 
     File dir = new java.io.File (root, "pdf"); 
     dir.mkdir(); 
     File writeTo = new File(root, "pdf/" + attachmentName); 
     FileOutputStream to = new FileOutputStream(writeTo); 

     byte[] buffer = new byte[4096]; 
     int bytesRead; 

     while ((bytesRead = from.read(buffer)) != -1) 
      to.write(buffer, 0, bytesRead); // write 
     to.close();    
     from.close(); 
    } else { 
     Log.d(TAG, "Unable to access SD card."); 
    } 
} catch (Exception e) { 
    Log.d(TAG, "writeToSDCard: " + e.getMessage()); 
} 
}  
} 
+0

仍然不能算起來,我還是謝謝你 – Rick

+0

哪一部分是搞亂你? – nickfox

+0

我已經知道了,謝謝您的支持,將發佈我的更新代碼以供可能需要它的人員參考。 – Rick

相關問題