摘要:
下文使用Java代码中获取路径的方法分享,如下所示:
实现思路:
使用java.io.File类中的方法,即可实现文件路径获取
getPath():返回表示用于创建关联File对象的路径的字符串
getAbsolutePath():当路径字符串是相对的,则在解析当前目录后返回路径字符串,从而产生一个完整的路径
getCanonicalPath():此方法在解析当前目录的任何相对路径后返回路径字符串,并删除任何相对路径元素,如 (.和..)
例:
Java 中获取文件路径的示例
package com.maomao365;
import java.io.File;
import java.io.IOException;
/**
* @author maomao365
*/
public class FilePathExample {
public static void main(String[] args) throws IOException {
File file=new File("../../maomaotest.txt");
System.out.println();
if(file.exists()){
String t1=file.getPath();
System.out.println("路径 : "+t1);
String t2=file.getAbsolutePath();
System.out.println("完整路径: "+t2);
String t3=file.getCanonicalPath();
System.out.println(":"+t3);
}else{
System.out.println("文件不存在!");
}
}
}