B
B
BitNeBolt2020-06-10 08:58:16
Android
BitNeBolt, 2020-06-10 08:58:16

How to write a file to phone storage?

The file must be created in the folder selected by the user. For this I want to use intent, ACTION_CREATE_DOCUMENT.

The file is created, but without content.

Invocation call:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TITLE, "test.txt");

                startActivityForResult(intent, CHOOSE_DIR_CODE);


Treatment:
switch (requestCode)
        {
            case CHOOSE_DIR_CODE:
                if (resultCode == RESULT_OK && data != null)
                {
                    try
                    {
                        FileOutputStream fos = new FileOutputStream("test.txt");//getContentResolver().openOutputStream(data.getData());

                        fos.write("Test".getBytes());

                        fos.close();

                        Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
                    } catch (FileNotFoundException e)
                    {
                        e.printStackTrace();

                        Toast.makeText(this, "WRONG 1", Toast.LENGTH_LONG).show();
                    } catch (IOException e)
                    {
                        Toast.makeText(this, "WRONG 2", Toast.LENGTH_LONG).show();

                        e.printStackTrace();
                    }
                }

                break;
        }


But a FileNotFoundException is thrown. The documentation says the following about it:
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.


How can you identify a particular case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Vodakov, 2020-06-10
@WaterSmith

Not to write here about all the possible reasons. I'll just leave you a link to a detailed guide on working with files:
forum.startandroid.ru/viewtopic.php?f=26&t=860

B
BitNeBolt, 2020-06-10
@BitNeBolt

Use Content Provider

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question