开发者

Why does my file.exists() always return false?

开发者 https://www.devze.com 2023-03-21 02:21 出处:网络
I store a photo taken by the camera like so: FileOutputStream out = new FileOutputStream(\"img_example\");

I store a photo taken by the camera like so:

FileOutputStream out = new FileOutputStream("img_example");
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);

In the onCreate() method (of the same activity/file) I check if the file exists but I must be doing something wrong because it doesn't go inside the following test:

file = getApplicationContext().getFileStreamPath("img_example");
if(file.exists()) 
{
    //doesn't go in here
}

I suspect it's something to do with the path or the context I've given.


Background Info: I actually have 3 different instances开发者_运维技巧 of the above code. Inside the file.exists() test I display a tick next to the "take image" button. Eventually, I'll want to retrieve the image in another activity but for now I just want to check if it exists


The most obvious reason is "because it isn't there".

I note that your code is creating the file in the "current directory", and looking for the file in the application context. Apparently they are not the same place. Why not just ...

FileOutputStream out = new FileOutputStream(
        getApplicationContext().getFileStreamPath("img_example"));


As it says in the android documentation:

getFileStreamPath(String name)

Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.

Why not write your file using the openFileOutput() method?

0

精彩评论

暂无评论...
验证码 换一张
取 消