Create file in specified directory

CVS picture CVS · Dec 3, 2012 · Viewed 7.4k times · Source

Try to create file in specific directory but it shows the error FileNotFound. Why? Am I using impossible path? I really don't know, but is seems like the code should be working.

    String day=/1;
String zn="/zn";
    File_name=zn
String root= Environment.getExternalStorageDirectory().toString();            
    File_path=root+day;

        File file1 = new File(File_path,File_name);
        file1.mkdirs();
        if(!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 


        try {
            OutputStream fos= new FileOutputStream(file1);
            String l,d,p;
            l = lessnum.getText().toString();
            d = desc.getText().toString();
            p = place.getText().toString();

            fos.write(l.getBytes());
            fos.write(d.getBytes());
            fos.write(p.getBytes());

            fos.close();

Answer

ρяσѕρєя K picture ρяσѕρєя K · Dec 3, 2012

Change your code as for creating a file on sdcard

String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";


File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
    try {
         file1.createNewFile();
       } catch (IOException e) {
          e.printStackTrace();
      }
} 

In current you you are also missing file Extension with file name so change String zn as zn="/zn.txt";

and make sure you have added Sd card permission in AndroidManifest.xml :

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