在应用程序中创建 CSV 或 TXT 文件并将其保存到“下载”文件夹 - Android

l00*_*00l 4 csv android opencsv android-download-manager android-storage

在问这个问题之前我进行了很多搜索和尝试。但我尝试的所有代码都不起作用。我希望该文件存储在该download文件夹中,并且在用户卸载该应用程序时也可以访问该文件。我也尝试过使用opencsv库。您能否提供一种tested创建csvtxt文件并将其存储到download文件夹的方法?

den*_*pto 5

保存到 publicDir(下载文件夹),您首先需要权限。WRITE_EXTERNAL_STORAGE 检查文档

请注意,如果没有权限,这将无法工作

   private void saveData(){

    String csv_data = "";/// your csv data as string;
    File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

    //if you want to create a sub-dir
    root = new File(root, "SubDir");
    root.mkdir();

    // select the name for your file
    root = new File(root , "my_csv.csv");

    try {
        FileOutputStream fout = new FileOutputStream(root);
        fout.write(csv_data.getBytes());

        fout.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();

        boolean bool = false;
        try {
            // try to create the file
            bool = root.createNewFile();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        if (bool){
            // call the method again
            saveData()
        }else {
            throw new IllegalStateException("Failed to create image file");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
   }
Run Code Online (Sandbox Code Playgroud)