petehallw
petehallw

Reputation: 1014

Writing to file using getFilesDir() giving 'Read-only file system' error (Android)

I want to write to my application's internal file directory but I am getting the following error:

java.io.FileNotFoundException: com.android.internal.os.AndroidPrintStream@47a0990 (Read-only file system)

So it says it is 'read-only' storage. I am using getFilesDir() to retrieve the path and I have seen lots of examples online of people using this to write to the internal storage. Why am I seeing this error?

My code is below:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();

// Root element
Element rootElement = doc.createElement("license");
doc.appendChild(rootElement);

// Write content to XML file.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(context.getFilesDir().getPath() + "/license.xml"));
System.out.println("Saving to: " + context.getFilesDir().getPath());
transformer.transform(source, result);

The exception is thrown at the final line of my code.

I have the following permissions in my Manifest:

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Note, I don't want to write to external storage as this file should not be visible to users.

I can write to the same directory using a FileOutputStream without it throwing any exception...so why does the Transformer encounter this read-only issue?

Upvotes: 2

Views: 1222

Answers (1)

Vyacheslav
Vyacheslav

Reputation: 27211

getFilesDir() is /data/data/com.example.apk/files

You need not to use those permissions.

It says filenotfound. Try to create it first.

Nevertheless, it's strange

Upvotes: 1

Related Questions