有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法编写。将csv应用到安卓的移动存储中

我已将db文件转换为csv文件,并在安卓中运行良好。但我从存储位置手动删除了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) 个答案

  1. # 1 楼答案

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

    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();
    }