java - 获取文件路径

标签 java file

有没有办法获取计算机上存在的文件的完整路径? 例如,我想获取桌面上文件夹中文件的完整路径

我尝试使用:

  File f = new File("help.chm");

  String f2=f.getAbsolutePath();
  f3=f3.replaceAll("\\\\","/" );
  System.out.println("Path:"+f3);

但它给了我这样的项目路径:

C:/Users/toshiba/Documents/NetBeansProjects/test/help.chm

虽然该文件不位于那里。

最佳答案

如果使用new File("filename")创建文件,即相对路径,则无法获取绝对路径使用file.getAbsolutePath()获取文件,因为相对路径是根据默认用户主目录或JVM路径构建的。

看看Java Doc :-

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. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

因此,要获取本例的绝对路径,您实际上必须自己编写路径。获取绝对路径直到保存文件的目录,并将文件名附加到其中。

关于java - 获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903436/

相关文章:

java - 什么是 alertcontroller.recyclelistview

java - 如何返回给定输入句子(字符串)的单词数组?

java - SQLException : No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

java - 如何在构建的 jar 中包含文本文件? [NetBeans]

java - 即使文件夹存在, file.listFiles() 返回 null

java - 在 try catch block 之外使用变量 (Java)

java - 如何在 java spring boot 中将字节数组作为内存文件返回?

java - 从数组中删除唯一值

java - 如何创建可读的传递参数? java

linux - Bash 将 ls 错误写入文件