Archanaa Sankar
Archanaa Sankar

Reputation: 21

Android File Creation

I am trying to create a file in a public directory in Android.

It works with most devices, but I am facing problems with Android Mini PC. I am able to create a folder in that, but not able to create a file.

String iconsStoragePath =  Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES).getAbsolutePath()+"/ab";
File dir = new File(iconsStoragePath);
dir.mkdirs();
File file = new File(iconsStoragePath, info.path.toString().replace("/", ""));

Upvotes: 2

Views: 58

Answers (1)

Mauker
Mauker

Reputation: 11497

First of all, don't forget to declare the correct permissions on your AndroidManifest.xml.

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

Then, check if the external storage is mounted.

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

Don't forget to check if the storage has enough space to save the file using File.getFreeSpace().

Now, try the following:

File dir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MOVIES);
if (!dir.mkdirs()) {
    Log.w("LOG","Directory not created!");
    // Handle this error here, or return.
}

File file = new File(dir, "YourFile.txt");

// Do whatever you want now like the example below...
try {
    FileOutputStream fos = new FileOutputStream(file);
    PrintWriter pw = new PrintWriter(fos);
    pw.println("Hello world!");
    pw.flush();
    pw.close();
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
    Log.i("Your_TAG", "File not found! Don't forget WRITE_EXTERNAL_STORAGE on your manifest!");
} catch (IOException e) {
    e.printStackTrace();
    Log.e("Your_TAG","Some IO error occurred...");
}  

For more information on that, you can check this tutorial on how to save files, and the docs on the Environment class.

Upvotes: 1

Related Questions