Search code examples
androidcsvuriexport-to-csv

Overwriting an existing file in external storage using its URI [android]?


I have an app that imports data from a .csv file by using its URI and a Scanner. It works like this:

private List<String[]> loadCSVfromURI(Uri file) throws FileNotFoundException, IOException {

    Scanner csvFileScanner = new Scanner(new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(file))));

    List<String[]> csvROW = new ArrayList<>();
    int tempRow = 0;
    while(csvFileScanner.hasNextLine()){
        String line = csvFileScanner.nextLine(); // Get single line from reader
        String[] splitLine = line.split(",");
        csvROW.add(tempRow, splitLine);
        tempRow++;
    }
    return csvROW;
}

My application has now edited the imported data (which was stored in a list of String arrays) and returned it to a single String. The data has been returned to a .CSV style format like so.

private String formatForCSV() {
    final String delimeter = "\n";
    StringBuilder formatCSVdata = new StringBuilder();
    String saveCSVrow;
    for(String[] thisRow: curCSV){
        saveCSVrow = String.join(",",thisRow);
        saveCSVrow = saveCSVrow + delimeter;
        formatCSVdata.append(saveCSVrow);
    }

    String saveCSV = formatCSVdata.toString();

    return saveCSV;
}

I now wish to save the String back to the original file, overwriting what was originally stored there but keeping the same location and file name. How can I perform the save/overwrite function using the URI from when the files data was first copied to my app?


Solution

  • So I resolved this issue using the Content Resolver and by using openOutputStream.

    OutputStream overWritter = null; //Outputstream to overwrite original content
        ContentResolver saveResolver = this.getContentResolver();
        try {
            overWritter = saveResolver.openOutputStream(originalURI);
            if (overWritter != null) {
                overWritter.write(myString.getBytes());
                overWritter.close();
                Toast.makeText(this, "Save Successful", Toast.LENGTH_LONG).show();
    
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Save Failure", Toast.LENGTH_LONG).show();
    
        }
    

    This saves and overwrites the file at the original URI. I am open to better solutions. Maybe something more robust.