本篇文章给大家谈谈java获取当前文件路径,以及java获取当前文件路径的方法对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
1、java获取指定资源文件路径的几种方法2、如何查看java读取文件的路径3、JAVA中如何得到文件路径4、java怎么获取本地文件路径
java获取指定资源文件路径的几种方法
你好,提问者:
指定资源路径的方法有两种:
一种是绝对路径,一种是相对路径。
获取当前类的所在工程路径;
File f = new File(this.getClass().getResource(“/”).getPath());
System.out.println(f);
获取当前类的绝对路径;
File f = new File(this.getClass().getResource(“”).getPath());
System.out.println(f);
获取当前类的所在工程路径;
File directory = new File(“”);//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
获取当前工程src目录下selected.txt文件的路径:
URL xmlpath = this.getClass().getClassLoader().getResource(“selected.txt”);
System.out.println(xmlpath);
如何查看java读取文件的路径
File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如file.getAbsolutePath()其中file是File的实例对象。下面是一个具体例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PathTest
{
public static void main(String[] args)
{
File file = new File(“.\\src\\baidu”);
System.out.println(file.getAbsolutePath());
try
{
System.out.println(file.getCanonicalPath());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中.(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。
下面是上面程序在我电脑上的输出:
G:\xhuoj\konw\.\src\baiduG:\xhuoj\konw\src\baidu
JAVA中如何得到文件路径
java文件中获得路径
Thread.currentThread().getContextClassLoader().getResource(“”) //获得资源文件(.class文件)所在路径
ClassLoader.getSystemResource(“”)
Class_Name.class.getClassLoader().getResource(“”)
Class_Name.class .getResource(“/”)
Class_Name.class .getResource(“”) // 获得当前类所在路径
System.getProperty(“user.dir”) // 获得项目根目录的绝对路径
System.getProperty(“java.class.path”) //得到类路径和包路径
打印输出依次如下:
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/com/xml/imp/
F:\work_litao\uri_test
F:\work_litao\uri_test\WebContent\WEB-INF\classes;F:\work_litao\uri_test\WebContent\WEB-INF\lib\dom4j.jar
java怎么获取本地文件路径
写了一个读取本地文件的方法, File file = new File(htmlFile); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); while((s=br.readLine())!=null){ al.add(s); } 在当前类写了main方法测试了一下是可行的, 但是页面某方法想调用该方法,不能实现。 总结问题是:只有放在static方法中可行,在其他地方调用都显示找不到指定文件。 文件结构: 把本地文件放在了web-inf的classes下了,相对路径写的(“/file.txt”); 求教为啥static方法可以,其他地方调用不行,这个函数本身不是静态的啊。
关于java获取当前文件路径和java获取当前文件路径的方法的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。