
FileDialog fileDialog = new FileDialog(this, "选择文件", FileDialogLOAD);
fileDialogsetVisible(true);
filePath = fileDialoggetDirectory();//获取文件的路径
textsetTex(filePath)
File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如filegetAbsolutePath()其中file是File的实例对象。下面是一个具体例子:
public class PathTest{
public static void main(String[] args)
{
File file = new File("\\src\\baidu");
Systemoutprintln(filegetAbsolutePath());
try
{
Systemoutprintln(filegetCanonicalPath());
} catch (IOException e)
{
eprintStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。
下面是上面程序在我电脑上的输出:
G:\xhuoj\konw\\src\baidu
G:\xhuoj\konw\src\baidu
平时写程序的时候,很多时候提示文件找不到,而抛出了异常,现在整理如下 一 相对路径的获得 说明:相对路径(即不写明时候到底相对谁)均可通过以下方式获得(不论是一般的java项目还是web项目) String relativelyPath=SystemgetProperty(
getClass()getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)
例如 项目在/D:/workspace/MainStream/Test
在javaProject中,getClass()getResource("/")getFile()toString() 返回:/D:/workspace/MainStream/Test/bin/
public String getCurrentPath(){//取得根目录路径
String rootPath=getClass()getResource("/")getFile()toString();
//当前目录路径
String currentPath1=getClass()getResource("")getFile()toString();
String currentPath2=getClass()getResource("")getFile()toString();
//当前目录的上级目录路径
String parentPath=getClass()getResource("/")getFile()toString();
return rootPath;
}
参考资料:
以上就是关于Java怎样获取一个文件的绝对路径全部的内容,包括:Java怎样获取一个文件的绝对路径、在java项目中如何获取某个文件的路径、java 怎样获取java工程中文件路径等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)