Write file to sdcard in android

android, android-sdcard, file

Solution

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);
}

Problem

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(); } ```

Original source