0

Is there any way to write in internal storage in Android? I tried the following from google developer site-

File file = new File(context.getFilesDir(), filename);

String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;

try {
    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    outputStream.write(fileContents.getBytes());
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

The problem is that whenever I uninstalls the app the file is also deleted. However I am required to keep that file even after uninstalling the App...

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Rony
  • 9
  • 1
  • 1
    that time you need to store file in external storage. –  May 14 '18 at 11:37
  • 1
    context.getFilesDir() returns your application dir "/data/data/your package/files". This folder is deleted when you uninstall your app. You should consider placing your files in other directory. – Sebastian M May 14 '18 at 11:38
  • rerefer this link https://stackoverflow.com/questions/8330276/write-a-file-in-external-storage-in-android –  May 14 '18 at 11:41

2 Answers2

1

You have to define which type of file you are try to create like.

FileType = "image"; FileType = "text";

Define filetype in your code.

Praveen Kumar
  • 277
  • 2
  • 12
0

When you use context.getFilesDir() you're accessing the project files directory. If you want to save it externally, you should use something like Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) instead and use permissions in your Android Manifest:

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

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

You can look for other directories here.