【问题标题】:how can I get file name and path in java?如何在java中获取文件名和路径?
【发布时间】:2012-02-16 09:28:20
【问题描述】:

我在他的名字动态更改的目录中有一个 zip 文件。 当我点击一个按钮时,我应该能够获得该文件的完整路径以及如下名称:U:\home\ash\dfi\dfiZipedFile\dfi.zip

public static String getFileFullName(BcfiDownloadPanel bcfiDownloadPanel) {
    File dir = new File("U:\\home\\ash\\dfi\\dfiZipedFile");

    String[] filesList = dir.list();
    if (filesList == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i = 0; i < filesList.length; i++) {
            // Get filename of file or directory
            String filename = filesList[i];
        }
    }
    String fileFullName = filesList[0];

    return fileFullName;
}

【问题讨论】:

  • 该目录中是否只有一个 ZIP?你怎么知道目录,但不知道文件名?该代码如何编译?

标签: java file directory filepath


【解决方案1】:
public static String getFirstZipFilename(File dir) {        
    for (File file : dir.listFiles()) {
        String filePath = file.getPath();
        if (file.isFile() && filePath.endsWith(".zip")) {
            return filePath;
        }
    }

    return null;
}
  • 适用于任何目录(尝试使您的实用程序方法通用...)
  • 找到有效文件后立即返回(没有无用的测试)
  • 如果未找到任何内容,则返回 null,以便您了解并显示警告消息

【讨论】:

  • 首先,您不应该使用断言来检查公共 API 中的先决条件。其次,断言是多余的,因为调用 dir.listFiles() 会立即取消对 dir 引用的引用。
  • 第二点为真。关于第一个,这取决于该类是否打算在公共图书馆中使用。但是,有疑问,您是对的,我将编辑答案。
【解决方案2】:

类似

String ret = null;

File dir = new File("U:/home/ash/dfi/dfiZipedFile");
File[] files = dir.listFiles();
for (File file : files)
{
  if (!file.isDirectory())
  {
    ret = file.getPath();
    break;
  }
}

return ret;

返回目录中第一个文件的完整路径。

【讨论】:

  • 这应该像上面提到的那样被纠正File dir = new File("U:\\home\\ash\\dfi\\dfiZipedFile");
  • 如果有更多其他灭绝的文件怎么办。我怎样才能拒绝其他扩展?
  • 您可以在 listFiles 中使用 FilenameFilter 或使用 filePath.toLowerCase().endsWith(".zip") 测试 filePath
  • 我认为 File("U:/home/ash/dfi/dfiZipedFile") 工作正常。那有什么问题。我不知道 File("U:\\home\\ash\\dfi\\dfiZipedFile") 是否适用于 Unix 机器。
【解决方案3】:

如果这段代码能工作,我会惊呆的。

您应该将文件名中的\ 替换为\\

【讨论】:

  • 这应该是对原始问题的评论。
  • @james.garriss 目的是帮助他。我的回答将使他的代码编译,因此它是答案的“一部分”,而不是纯粹的评论。所以两者都有效,无论是评论还是答案。老实说,我寻求答案是因为被投票的 cmets 不会给你积分..
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
相关资源
最近更新 更多