Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?

// create file
    public void createfile(String name) 
    {
        try
        {
            new FileOutputStream(filename, true).close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // write to file

    public void appendToFile(String dataAppend, String nameOfFile) throws IOException 
    {
        fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
        fosAppend.write(dataAppend.getBytes());
        fosAppend.write(System.getProperty("line.separator").getBytes());
        fosAppend.flush();
        fosAppend.close();
    }
like image 394
Looking Forward Avatar asked Dec 12 '22 09:12

Looking Forward


2 Answers

Here's an example from my code:

try {
    String filename = "abc.txt";
    File myFile = new File(Environment
            .getExternalStorageDirectory(), filename);
    if (!myFile.exists())
        myFile.createNewFile();
    FileOutputStream fos;
    byte[] data = string.getBytes();
    try {
        fos = new FileOutputStream(myFile);
        fos.write(data);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

And don't forget the:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
like image 147
Rakeeb Rajbhandari Avatar answered Jan 20 '23 07:01

Rakeeb Rajbhandari


Try like this,

try {
    File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
    if (!newFolder.exists()) {
        newFolder.mkdir();
    }
    try {
        File file = new File(newFolder, "MyTest" + ".txt");
        file.createNewFile();
    } catch (Exception ex) {
        System.out.println("ex: " + ex);
    }
} catch (Exception e) {
    System.out.println("e: " + e);
}
like image 35
Gunaseelan Avatar answered Jan 20 '23 05:01

Gunaseelan