1
votes

I am using following code in android to create a file :

File path = new File(this.context.getFilesDir() + File.separator + "A");
        File file = null;

        if (!path.exists()){
            //print log 1
            if (! path.mkdirs()){
                //print log 2
            } else {
                //print log 3
                file = new File(path.getAbsolutePath(),"A.json");
            }
        } else {
            //print log 4
            file = new File(path.getAbsolutePath(),"A.json");
            if (file.exists())
            {
                //print log 5
            } else {
                //print log 6
            }
        }
InputStream is = new FileInputStream(file);

Problem:- When i install the APK , first time the above code works . I get the logs : //print log 1, print log 3 . Then i am able to get the input stream.

But next time when this code executes , it goes to print log 4 , print log 5. But when i try to get the input stream it gives me error : java.io.FileNotFoundException: /data/data/com.abc.android.abc/files/A/A.json: open failed: ENOENT (No such file or directory)

1
Then i am able to get the input stream.. Impossible. You just created directory 'A' and then there would already be a file 'A.json' in it? Impossible.greenapps
Your code is terrible in many ways. For instance if mkdirs() fails you even try to open the input stream. You should return then. No further execution.greenapps
I am using following code in android to create a file :. There is nothing in your code that creates a file.greenapps
@greenapps thanks for comments. I am aware about how to handle if mkdirs fails . But thats not the point i am asking .Pardeep Kr

1 Answers

0
votes

whereever you are defining f. You are defining File path and file and try to get an inputstream from f