如何从sd卡或android中的指定路径读取csv文件

时间:2011-07-18 03:00:12

标签: java android csv import

  

可能重复:
  reading a specific file from sdcard in 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。

帮助将受到高度赞赏!谢谢,快乐的编码!

2 个答案:

答案 0 :(得分:3)

以前在Stack Overflow上已经介绍了从SDCard读取文件。

这是链接:

答案 1 :(得分: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());
}
}       
}