无法将.csv写入android中的移动存储

时间:2017-02-10 09:56:26

标签: java android

我已将db文件转换为csv文件并在android中完美运行。但是我从存储位置手动删除了csv文件并尝试运行相同的代码。但我无法将文件写入同一位置。没有异常注意到。 使用的代码如下:

    public void exportTopic() {
        int rowCount, colCount;
        int i, j;
        Cursor c=null;
        SQLHelper helperr=null;
        try {
            helperr=new SQLHelper(getActivity());
            c = helperr.getAllTopics();
            Log.d("exportPath", sdCardDir.getPath());
            String filename = "MyBackUp.csv";
            File CsvFile = new File(sdCardDir, filename);
            FileWriter fw = new FileWriter(CsvFile);
            BufferedWriter bw = new BufferedWriter(fw);
            rowCount = c.getCount();
            colCount = c.getColumnCount();
            if (rowCount > 0) {
                c.moveToFirst();
                for (i = 0; i < rowCount; i++) {
                    c.moveToPosition(i);
                    for (j = 0; j < colCount; j++) {
                        if (j != colCount - 1)
                            bw.write(c.getString(j) + ",");
                        else
                            bw.write(c.getString(j));
                    }
                    bw.newLine();
                }
                bw.flush();
            }
        } catch (Exception ex) {
            Log.d("Exception","at export topic");
            helperr.close();
            ex.printStackTrace();
        }
        helperr.close();
        c.close();

    }

我从这里调用函数:

   private View.OnClickListener clickHandler = new View.OnClickListener() {

    @Override
    public void onClick(View v) {

           if (v.getId() == R.id.exportToDropBtn) {
            try {
                exportTopic();

            }catch (Exception e){
                Log.d("Exception","at export button");
                e.printStackTrace();
            }
        }

1 个答案:

答案 0 :(得分:0)

添加代码以创建不存在的文件:

File dir = new File(Environment.getExternalStorageDirectory() + "/yourAppName");
// make them in case they're not there
dir.mkdirs();

File wbfile = new File(dir, fileName);
try {
        if (!wbfile.exists()) {
            wbfile.createNewFile();
        }

        // BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(
                new FileWriter(wbfile, true));
        buf.append(strBuilder.toString());
        buf.newLine();
        buf.close();
   } catch(Exception e){
   e.printStackTrace();
}