读书人

java 资料读写 路径配置

发布时间: 2012-12-26 14:39:29 作者: rapoo

java 文件读写 路径配置
java 文件读写,路径配置总结:

1. File 对象的getAbsoluteFile(),getAbsolutePath()方法,文件放在项目下面。
FileInputStream fio = new FileInputStream(new File("information.properties").getAbsoluteFile());
FileInputStream fio = new FileInputStream(new File("information.properties").getAbsolutePath());

项目结构:

project name
|_src
|
|_file position

2.Class 对象的getResourceAsStream()方法。文件放在java源文件同一目录。
InputStream fio = TestProperties.class.getResourceAsStream("information.properties");

项目结构:

project name
|_src+
|_com
|_java 源文件
|_file position

3.类加载器读取文件,文件应放在src目录下(以下面例子为例,应和com同级)。
Thread.currentThread().getContextClassLoader().getResourceAsStream("information.properties");
System.out.println(TestProperties.class.getClassLoader().getResourceAsStream("information.properties"));
System.out.println(ClassLoader.getSystemResource("information.properties"));

项目结构:

project name
|_src+
|_com
|_java 源文件
|_file position
4.直接使用File构造器,使用文件的相对路径作为参数传入到构造器。文件应放在项目下面。
FileInputStream fio = new FileInputStream(new File("information.properties"));
项目结构:

project name
|_src
|
|_file position

5.使用System.getProperties("user.dir"),文件应放在项目下面。

System.out.println(System.getProperty("user.dir")+
"\\information.properties");
项目结构:

project name
|_src
|
|_file position

读书人网 >编程

热点推荐