检查文件是否存在于特定目录中 [英] checking if file exists in a specific directory

查看:119
本文介绍了检查文件是否存在于特定目录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查给定目录中的特定文件。我不想要代码,但我想修复我有一个。这个问题的唯一区别是,我查找扩展名为 .MOD 的文件。



我有代码准备: -

  public static int checkExists(String directory,String file){
文件dir = new File目录);
文件[] dir_contents = dir.listFiles();
String temp = file +.MOD;
boolean check = new File(temp).exists();
System.out.println(检查+检查); //对于(int i = 0; i if(dir_contents [i] .getName()==( file +.MOD))
返回Constants.FILE_EXISTS;
}

返回Constants.FILE_DOES_NOT_EXIST;
}

但由于某些原因,它不工作。我不明白为什么,任何人都可以在这里找到任何错误?

解决方案

您是否希望temp.MOD文件位于当前目录(运行应用程序的目录),或你想要在目录文件夹中?在后一种情况下,尝试以这种方式创建文件:

  boolean check = new File(directory,temp).exists() ; 

同时检查文件权限,因为它也将在权限错误失败。敏感的案件也可能是Spaeth提到的问题的原因。


Hey guys I am trying to check for a specific file in a given directory. I dont want the code but I want to fix the one I have. The only difference in this question, is that I look for files with an extension .MOD.

I have the code ready:-

public static int checkExists(String directory, String file) {
    File dir = new File(directory);
    File[] dir_contents = dir.listFiles();
    String temp = file + ".MOD";
    boolean check = new File(temp).exists();
    System.out.println("Check"+check);  // -->always says false

    for(int i = 0; i<dir_contents.length;i++) {
        if(dir_contents[i].getName() == (file + ".MOD"))
            return Constants.FILE_EXISTS;
    }

    return Constants.FILE_DOES_NOT_EXIST;
}

But for some reasons, it doesnot work. I dont understand why, can anybody find any bug here?

解决方案

Do you expect temp.MOD file to be in the current directory (the directory from which you run your application), or you want it to be in the "directory" folder? In the latter case, try creating the file this way:

boolean check = new File(directory, temp).exists();

Also check for the file permissions, because it will fail on permission errors as well. Case sensitivily might also be the cause of the issue as Spaeth mentioned.

这篇关于检查文件是否存在于特定目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆