在java中获取文件完整路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2981972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:13:34  来源:igfitidea点击:

Get file full path in java

java

提问by ant

When I pass File fileto a method I'm trying to get its full path like file.getAbsolutePath();I always get the same result no matter which one I use either absolute or canonical path PATH_TO_MY_WORKSPACE/projectName/filenameand it is not there, how can I get exact location of the file?

当我传递File file给一个方法时,我试图获得它的完整路径,就像file.getAbsolutePath();我总是得到相同的结果,无论我使用绝对路径还是规范路径PATH_TO_MY_WORKSPACE/projectName/filename,它都不存在,我怎样才能获得文件的确切位置?

Thank you

谢谢

DETAILS:

细节:

Here is some code and this solutions(its bad but its working):

这是一些代码和这个解决方案(它不好,但它的工作原理):

 private static void doSomethingToDirectory(File factDir) throws IOException {
            File[] dirContents = factDir.listFiles();

            if(factDir.isDirectory() && dirContents.length > 0){
                for (int i = 0; i < dirContents.length; i++) {
                    for (String str : dirContents[i].list()) {
                        if(str.equals(TEMP_COMPARE_FILE)){
                            process(new File(dirContents[i].getAbsolutePath() + "\" + str));
                        }
                    }
                }           
            }
        }

I'm looping trough directories where factDir is src/main, I'm seeking toBeProcessed.txt files only that is TEMP_COMPARE_FILE value and I'm sending them to process method which reads the file and does processing of it.

我正在循环遍历 factDir 所在的目录src/main,我正在寻找 toBeProcessed.txt 文件,只有 TEMP_COMPARE_FILE 值,我将它们发送到读取文件并对其进行处理的处理方法。

If someone could better solution I'd be greatful

如果有人能提供更好的解决方案,我会很高兴

采纳答案by Péter T?r?k

This quote from the Javadocmight be helpful:

Javadoc 中的这句话可能会有所帮助:

A pathname, whether abstract or in string form, may be either absoluteor relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.iopackage always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

路径名,无论是抽象的还是字符串形式的,都可以是绝对的相对的。绝对路径名是完整的,因为不需要其他信息来定位它表示的文件。相反,相对路径名必须根据取自其他路径名的信息进行解释。默认情况下,java.io包中的类总是针对当前用户目录解析相对路径名。该目录由系统属性命名user.dir,通常是调用 Java 虚拟机的目录。

I interpret this so that if you create your Fileobject with new File("filename")where filenameis a relative path, that path will not be converted into an absolute path even by a call to file.getAbsolutePath().

我解释了这一点,以便如果您File使用new File("filename")wherefilename是相对路径创建对象,即使调用file.getAbsolutePath().

Update:now that you posted code, I can think of some ways to improve it:

更新:既然你发布了代码,我可以想到一些改进它的方法:

  • you could use a FilenameFilterto find the desired files,
  • note that listand listFilesreturn nullfor non-directory objects, so we need an extra check for that,
  • you could also use listFiles()again in the inner loop, thus avoiding the need to create new Fileobjects with hand-assembled paths. (Btw note that appending \\manually to the path is not portable; the proper way would be to use File.separator).
  • 您可以使用FilenameFilter来查找所需的文件,
  • 请注意listlistFiles返回null非目录对象,因此我们需要对此进行额外检查,
  • 您也可以listFiles()在内部循环中再次使用,从而避免File使用手动组装路径创建新对象的需要。(顺便说一句,\\手动附加到路径是不可移植的;正确的方法是使用File.separator)。

The end result is

最终结果是

private static void doSomethingToDirectory(File factDir) throws IOException {
  if (factDir.isDirectory()) {
    for (File file : factDir.listFiles()) {
      if (file.isDirectory()) {
        for (File child : file.listFiles(new MyFilter())) {
          process(child);
        }
      }
    }           
  }
}

class MyFilter implements FilenameFilter {
  public boolean accept(File dir, String name) {
    return name.equals(TEMP_COMPARE_FILE);
  }
}

Note that this code mimics the behaviour of your original piece of code as much as I understood it; most notably, it finds the files with the proper name only in the direct subdirectoriesof factDir, nonrecursively.

请注意,这段代码模仿了我所理解的原始代码段的行为;最值得注意的是,它仅在 的直接子目录中factDir非递归方式查找具有正确名称的文件。

回答by Adham Gamal

I think there is a way it may help you if and only if the file is in the program directory.

我认为有一种方法可以帮助您,当且仅当文件位于程序目录中时。

first you get the program directory by :

首先,您通过以下方式获取程序目录:

new File(".").getCanonicalPath()

then :

然后 :

if fileis inside a specific directory like folder\\filenamethe full path will be

如果file在特定目录内,如folder\\filename完整路径将是

(new File(".").getCanonicalPath() + "\folder\filename")

or if fileis directly inside the program directory: the full path will be

或者如果file直接在程序目录中:完整路径将是

(new File(".").getCanonicalPath() + "\filename")

i wish this answer help you :)

我希望这个答案对你有帮助:)