Jason Robinson
Jason Robinson

Reputation: 31283

Unable to cache an image to a file, says file does not exist

I'm hoping there is an obvious problem in my code I'm overlooking, but I'm verifying that the file that I am going to write to exists and can be written to. It crashes on fos = new FileOutputStream( file.getPath() ); with FileNotFound exception.

File file = new File( cacheDir, url.getFile() );
        if ( file.exists() ) {
            file.delete();
        }

        try {
            file.mkdirs();
            file.createNewFile();
        }
        catch (IOException e) {
            MyLog.e( "Unable to create file: " + file.getPath() );
        }

        if ( file.exists() && file.canWrite() ) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream( file );
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            if ( !bitmap.compress( CompressFormat.PNG, 100, fos ) ) {
                MyLog.e( "Unable to cache image: " + path );
            }

            if ( fos != null ) {
                try {
                    fos.flush();
                    fos.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

Upvotes: 0

Views: 301

Answers (1)

rochdev
rochdev

Reputation: 3855

I bet you have some funny characters in the file name.

Try

File file = new File( cacheDir, URLEncoder.encode(url.getFile()) );

Upvotes: 1

Related Questions