Home > OS >  Android: Create file using ACTION_CREATE_DOCUMENT then write to file
Android: Create file using ACTION_CREATE_DOCUMENT then write to file

Time:10-10

I am trying to export some data as a .csv file and wish to be able to save it in a named file using the Intent.ACTION_CREATE_DOCUMENT picker.

private void fileDemo() {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.setType("text/csv");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.putExtra(Intent.EXTRA_TITLE, "data.csv");
    startActivityForResult(intent, PICKFILE_RESULT_CODE);
}

which works fine and a zero byte correctly named file is created. I have also created a method which will export the CSV data as a file if I save the data to a file with a fixed name

    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOCUMENTS);
    File file = new File(path, "Waypoints.csv");
    try {
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

    // rest of code…

The difficulty is getting the second part of the code to accept a file from the first. The code I am using is

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == -1) {
                fileUri = data.getData();
                filePath = fileUri.getPath();
            }

            try {
                FileWriter fileWriter = new FileWriter(filePath); // FileNotFound exception here

                // file writing code goes here

            } catch (IOException e) {
                throw new RuntimeException(e);

which throws up a FileNotFound exception. I've spent the day looking through the documentation and the web but, so far, a brick wall. Any ideas?

CodePudding user response:

The difficulty is getting the second part of the code to accept a file from the first

You are not working with a file. Where ACTION_CREATE_DOCUMENT creates the document where the user wants it, which may or may not be a file on the filesystem.

Use ContentResolver and openOutputStream():

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == -1) {
              try {
                OutputStream os = getContentResolver().openOutputStream(data.getData());
                Writer writer = new OutputStreamWriter(os);

                // content writing code goes here

              } catch (IOException e) {
                throw new RuntimeException(e);
  • Related