file 获取路径
1、基本介绍
- getpath 方法:创建 file 对象时传入的原始路径
public string getpath() {
return path;
}
- getabsolutepath 方法:将相对路径与当前工作目录拼接,得到一个完整的绝对路径
public string getabsolutepath() {
return fs.resolve(this);
}
- 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、演示
- 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
- 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
- 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获取路径方式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论