在Java中,java.io.File 类提供了多种方法来获取文件的路径。以下是一些常用的方法:
getPath(): 返回构造File对象时传入的路径字符串。File file = new File("example.txt");
String path = file.getPath(); // 返回 "example.txt"
getAbsolutePath(): 返回文件的绝对路径名字符串。如果构造File对象时传入的是相对路径,则该方法会将其转换为绝对路径。File file = new File("example.txt");
String absolutePath = file.getAbsolutePath(); // 返回 "/Users/username/project/example.txt"(假设当前用户目录为/Users/username/project)
getCanonicalPath(): 返回文件的规范路径名字符串。该方法会解析符号链接、相对路径等,并返回一个规范化的绝对路径。File file = new File("example.txt");
try {
String canonicalPath = file.getCanonicalPath(); // 返回 "/Users/username/project/example.txt"(假设当前用户目录为/Users/username/project)
} catch (IOException e) {
e.printStackTrace();
}
请注意,getCanonicalPath() 方法可能会抛出 IOException,因此需要使用 try-catch 语句处理异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。