Android; Check if file exists without creating a n

2019-01-04 06:19发布

I want to check if file exists in my package folder, but I don't want to create a new one.

File file = new File(filePath);
if(file.exists()) 
     return true;

Does this code check without creating a new file?

6条回答
一夜七次
2楼-- · 2019-01-04 06:36
public boolean FileExists(String fname) {
        File file = getBaseContext().getFileStreamPath(fname);
        return file.exists();
}
查看更多
Evening l夕情丶
3楼-- · 2019-01-04 06:38

It worked for me:

File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
    if(file.exists()){
       //Do something
    }
    else{
       //Nothing
     }
查看更多
Anthone
4楼-- · 2019-01-04 06:41

Your chunk of code does not create a new one, it only checks if its already there and nothing else.

File file = new File(filePath);
if(file.exists())      
//Do something
else
// Do something else.
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-04 06:45

When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().

Sample code (in an Activity):

public void onCreate(...) {
    super.onCreate(...);
    String[] files = fileList();
    for (String file : files) {
        if (file.equals(myFileName)) {
            //file exits
        }
    }
}
查看更多
Deceive 欺骗
6楼-- · 2019-01-04 06:49

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.

File file = new File(filePath);
if(file.exists()) 
    //do something
查看更多
等我变得足够好
7楼-- · 2019-01-04 06:52

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

 File file = new File("FileName");
 if(file.exists()){
 System.out.println("file is already there");
 }else{
 System.out.println("Not find file ");
 }
查看更多
登录 后发表回答