4

I searched and tried a lot before asking this. But all the code that I'm trying is not working. I want the file to be stored in the download folder and be accessible from the user also if he uninstalls the app. I also tried using opencsv library. Could you provide a tested way to create a csv or txt file and store to download folder?

l000000l
  • 330
  • 1
  • 3
  • 14

1 Answers1

5

Save to to publicDir(Downloads folder) you first need permission.WRITE_EXTERNAL_STORAGE check docs

Note this won't work without permmissions

   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();
    }
   }
denniz crypto
  • 451
  • 4
  • 10