简体   繁体   English

在java中获取文件的完整路径

[英]Get file full path in java

When I pass File file to a method I'm trying to get its full path like file.getAbsolutePath(); 当我将File file传递给方法时,我正试图获得像file.getAbsolutePath(); I always get the same result no matter which one I use either absolute or canonical path PATH_TO_MY_WORKSPACE/projectName/filename and it is not there, how can I get exact location of the file? 我总是得到相同的结果,无论我使用绝对路径或规范路径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目录,我正在寻找只有TEMP_COMPARE_FILE值的BeProcessed.txt文件,并且我将它们发送到读取文件并对其进行处理的进程方法。

If someone could better solution I'd be greatful 如果有人能够更好地解决问题我会很高兴

This quote from the Javadoc might be helpful: 来自Javadoc的引用可能会有所帮助:

A pathname, whether abstract or in string form, may be either absolute or 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.io package always resolve relative pathnames against the current user directory. 默认情况下, java.io包中的类始终解析当前用户目录的相对路径名。 This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked. 此目录由系统属性user.dir命名,通常是调用Java虚拟机的目录。

I interpret this so that if you create your File object with new File("filename") where filename is a relative path, that path will not be converted into an absolute path even by a call to file.getAbsolutePath() . 我解释这一点,如果您使用new File("filename")创建File对象,其中filename是相对路径,即使通过调用file.getAbsolutePath() ,该路径也不会转换为绝对路径。

Update: now that you posted code, I can think of some ways to improve it: 更新:现在你发布了代码,我可以想办法改进它:

  • you could use a FilenameFilter to find the desired files, 您可以使用FilenameFilter来查找所需的文件,
  • note that list and listFiles return null for non-directory objects, so we need an extra check for that, 请注意, listlistFiles为非目录对象返回null ,因此我们需要额外检查,
  • you could also use listFiles() again in the inner loop, thus avoiding the need to create new File objects with hand-assembled paths. 你也可以在内部循环中再次使用listFiles() ,从而避免使用手工组装路径创建新的File对象。 (Btw note that appending \\\\ manually to the path is not portable; the proper way would be to use File.separator ). (顺便说一下,手动将\\\\附加到路径是不可移植的;正确的方法是使用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 subdirectories of factDir , nonrecursively. 最值得注意的是,它只在factDir直接子目录中找到具有正确名称的文件,非递归。

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 file is inside a specific directory like folder\\\\filename the full path will be 如果filefolder\\\\filename之类的特定目录中,则完整路径将是

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

or if file is directly inside the program directory: the full path will be 或者如果file直接位于程序目录中:完整路径将是

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

i wish this answer help you :) 我希望这个答案可以帮助你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM