Home > Net >  file.exists() always returns true no matter what
file.exists() always returns true no matter what

Time:07-27

I have this function that searches a directory for a file based on a given filename. My problem is that it always returns true (file exists) no matter what.

Here's the function:

public boolean searchFile(String name) {
    File localStorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    String storagePath = localStorage.getAbsolutePath();
    String rootPath = storagePath   "/App";
    String fileName = "/"   name   fileExtention;
    File root = new File(rootPath);
    if(!root.mkdirs()) {
        Log.i("test", "This path is already exist: "   root.getAbsolutePath());
    }
    File f = new File(rootPath   fileName);
    try {
        if (getActivity() != null) {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                if (f.exists()) {
                    Log.i("test", "This file is already exist: "   f.getAbsolutePath());
                    return true;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

This doesn't really make sense as I read that File f = new File(blah) only creates an Object of the File and doesn't actually create the file in the storage.

CodePudding user response:

Please find the function below, you can map it to fit your situation. I am using Java NIO. I have also suppressed all warnings @SuppressLint("NewApi")(this is not a must, suppressing the warnings that is)

Java Code

import android.annotation.SuppressLint;
import android.util.Log;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileExistAlwaysReturnsTrue {

    Path path;
    String LOG_TAG = "Files_Log";

    @SuppressLint("NewApi")
    boolean fileExists(String filePath /*Set the file path here*/) {

        /* Sample filePath: /data/data/com.package/cache/WebView/font_unique_name_table.pb */

        try {
            path = Paths.get(filePath);
            if (Files.exists(path)) {
                return true; /* File exists */
            } else {
                return false; /* File does exists */
            }
        } catch (Exception e) {
            Log.d(LOG_TAG, e.getMessage());
        }
        return false;
    }


}

Permissions

Ensure you have the following permission.

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

Regards

  • Related