当前位置: 代码网 > it编程>编程语言>Java > Java IO编程中File获取路径的3种方式

Java IO编程中File获取路径的3种方式

2026年08月27日 Java 我要评论
file 获取路径1、基本介绍getpath 方法:创建 file 对象时传入的原始路径public string getpath() { return path;}getabsolutepat

file 获取路径

1、基本介绍

  1. getpath 方法:创建 file 对象时传入的原始路径
public string getpath() {
    return path;
}
  1. getabsolutepath 方法:将相对路径与当前工作目录拼接,得到一个完整的绝对路径
public string getabsolutepath() {
    return fs.resolve(this);
}
  1. getcanonicalfile 方法:将相对路径与当前工作目录拼接,得到一个完整的绝对路径
public file getcanonicalfile() throws ioexception {
    string canonpath = getcanonicalpath();
    if (getclass() != file.class) {
        canonpath = fs.normalize(canonpath);
    }
    return new file(canonpath, fs.prefixlength(canonpath));
}

2、演示

  1. getpath 方法
file dir = new file("myproject");
file file = new file(dir, "test.txt");

system.out.println(file.getpath());
system.out.println(file.getabsolutepath());
try {
    system.out.println(file.getcanonicalfile());
} catch (ioexception e) {
    e.printstacktrace();
}
# 输出结果

myproject\test.txt
d:\javacode\javaproject\myproject\test.txt
d:\javacode\javaproject\myproject\test.txt
  1. getabsolutepath 方法
file dir = new file("./myproject");
file file = new file(dir, "test.txt");

system.out.println(file.getpath());
system.out.println(file.getabsolutepath());
try {
    system.out.println(file.getcanonicalfile());
} catch (ioexception e) {
    e.printstacktrace();
}
# 输出结果

.\myproject\test.txt
d:\javacode\javaproject\.\myproject\test.txt
d:\javacode\javaproject\myproject\test.txt
  1. getcanonicalfile 方法
file file = new file("src/../demo.txt");

system.out.println(file.getpath());
system.out.println(file.getabsolutepath());
try {
    system.out.println(file.getcanonicalfile());
} catch (ioexception e) {
    e.printstacktrace();
}
# 输出结果

src\..\demo.txt
d:\javacode\javaproject\src\..\demo.txt
d:\javacode\javaproject\demo.txt

到此这篇关于java io编程中file获取路径的3种方式的文章就介绍到这了,更多相关java file获取路径方式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com