有没有办法获取计算机上存在的文件的完整路径? 例如,我想获取桌面上文件夹中文件的完整路径
我尝试使用:
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/