【问题标题】:file.exists return false when folder is not empty当文件夹不为空时,file.exists 返回 false
【发布时间】:2015-09-21 05:25:31
【问题描述】:

我正在尝试访问远程共享位置中的文件。

////hostname//data//upload//123//test.txt
File sourceFile=new File("////hostname//data//upload//123//test.txt");
sysout("sourceFile.exists()"+sourceFile.exists())//returning false

如果目录为空,file.exists() 将返回 true。 我正在使用 Java 1.6

我不明白这是什么奇怪的行为。

【问题讨论】:

  • 你确定你需要写 // 而不是 \\ 吗?

标签: java file file-exists


【解决方案1】:

首先回到欧文的建议,这不是正确的尝试。字符\ 在Java 中用作转义序列,通常用于打印保留字符。比如会

String s = "The weather is really "nice" today";

导致错误,因为" 已为字符串保留。正确的版本是

String s = "The weather is really \"nice\" today";

回到问题,你必须知道,当你创建一个文件并测试它是否存在时Java会验证文件的抽象路径名。也就是说,如果您的抽象路径是一个目录并且它存在,true 将被返回。

编辑:
如果您打算检查抽象路径名是否为目录,请尝试以下操作:

// Check if a file is a directory
if(file.isDirectory()) {

}

// Check if a file contains something
if(file.list().length > 0) {

}

【讨论】:

  • 问题已修复,因为应用程序 Windows 服务未在正确的用户上运行。因此,由于缺乏权限,它抛出了这个异常。感谢大家的帮助。
【解决方案2】:

检查这个例子,它检查目录,否则创建一个新目录,然后创建你的新文件。

File f = new File("D:/image_send");
    File file = new File("D:/image_send/" + date + ".txt");
    try {
        if(!f.isDirectory()){
        f.mkdirs();
        }
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("File created Success");

【讨论】:

    【解决方案3】:
    public static boolean fileTransfer(String src, String des) throws Exception {
        if (des == null || des.equals("") || src == null || src.equals("")) {
            return false;
        }
        File fileExisting = new File(src);
         File fileNew = new File(des+ fileExisting.getName());
        if (fileExisting.exists() && !fileExisting.isDirectory()) {
            if (fileExisting.renameTo(fileNew)) {
                System.out.println("File is moved successful!");
            } else {
                System.out.println("File is failed to move!");
            }
    
        }
        return fileNew.exists();
    }
    

    这是根据您的评论进行文件传输的代码,如果您得到布尔值 false,则使用 src 作为源路径,使用 des 作为目标路径,这意味着给定的路径是错误的。

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2011-07-23
      • 2015-05-05
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多