ilbets
ilbets

Reputation: 768

Create file in specified directory

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

Upvotes: 3

Views: 7677

Answers (5)

user4232
user4232

Reputation: 592

First you make a directory

String root= Environment.getExternalStorageDirectory().toString();      
 String dirName =
     root+ "abc/123/xy"; 
     File newFile =  new File(dirName);
     newFile.mkdirs();

then you create a file inside that directory

String testFile = "test.txt"; File file1 = new File(dirName,testFile); if(!file1.exists()){ try { file1.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

then do your file writing operations

try { OutputStream fos= new FileOutputStream(file1);

String l,d,p; l = lessnum.getText().toString(); d = desc.getText().toString(); p = place.getText().toString(); os.write(l.getBytes()); fos.write(d.getBytes()); fos.write(p.getBytes()); fos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }

I think this will help you...

Thanks...

Upvotes: 1

Stephen C
Stephen C

Reputation: 719259

Here is your latest attempt:

File_path = root + File.separator + day; 
File f_dir = new File(File_path); 
f_dir.mkdirs(); 
File file1 = new File(f_dir, File_name); 
if (!file1.exists()) { 
    try { 
        file1.createNewFile(); 
    } catch (IOException e) {
        e.printStackTrace(); 
    } 
}
try { 
    OutputStream fos= new FileOutputStream(file1); 

If you showed us the complete stacktrace and error message it would be easier to figure out what is going wrong, but I can think of a couple of possibilities:

  1. You are not checking the value returned by f_dir.mkdirs(), and it could well be returning false to indicate that the directory path was not created. This could mean that:
    • The directory already existed.
    • Something existed but it wasn't a directory.
    • Some part of the directory path could not be created ... for one of a number of possible reasons.
  2. The file1.exists() call will return true if anything exists with that pathname given by the object. The fact that something exists doesn't necessarily mean that you can open it for writing:
    • It could be a directory.
    • It could be a file that the application doesn't have write permissions for.
    • It could be a file on a read-only file system.
    • And a few other things.

If I was writing this, I'd write it something like this:

File dir = new File(new File(root), day);
if (!dir.exists()) {
    if (!dir.mkdirs()) {
        System.err.println("Cannot create directories");
        return;
    }
}
File file1 = new File(dir, fileName);
try (OutputStream fos= new FileOutputStream(file1)) {
    ...
} catch (FileNotFoundException ex) {
   System.err.println("Cannot open file: " + ex.getMessage());
}

I only attempt to create the directory if required ... and check that the creation succeeded. Then I simply attempt to open the file to write to it. If the file doesn't exist it will be created. If it cannot be created, then the FileNotFoundException message should explain why.

Notice that I've also corrected the style errors you made in your choice of variable names.

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

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"/>

Upvotes: 1

user4232
user4232

Reputation: 592

String root= Environment.getExternalStorageDirectory().toString();      
     String dirName =
         root+ "abc/123/xy"; 
         File newFile =  new File(dirName);
         newFile.mkdirs();

         String testFile = "test.txt";
         File file1 = new File(dirName,testFile);
        if(!file1.exists()){
             try {
                file1.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

And and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> on manifest file...

Thanks...

Upvotes: 0

Nermeen
Nermeen

Reputation: 15973

you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

And check http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29

Upvotes: 0

Related Questions