gpt4 book ai didi

java - 获取文件路径

转载 作者:行者123 更新时间:2023-11-30 09:31:25 34 4
gpt4 key购买 nike

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

我尝试使用:

  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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com