Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create CSV or TXT file in app and save it to 'download' folder - Android

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?

like image 644
l000000l Avatar asked Sep 12 '25 17:09

l000000l


1 Answers

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();
    }
   }
like image 162
denniz crypto Avatar answered Sep 14 '25 06:09

denniz crypto