您的位置:首页 > 编程语言 > Java开发

java 加载资源方法

2015-06-25 23:04 337 查看
目录结构如下

/home/test / foo / conf / conf.txt                 (conf.txt 内容为a=b)

/home/ test / foo / cont.txt                            (conf.txt 内容为c=d)

/home/ test / conf / conf.txt                          (conf.txt内容为e=f)

/home/ test / foo / ResourceLoader.java

ResourceLoader.java代码如下:

package foo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ResourceLoader {
public static void main(String[] args) throws Exception {
ResourceLoader loader = new ResourceLoader();
loader.load();

loader.load2();

loader.load3();
}

public void load() {
try {
InputStream is = this.getClass().getResourceAsStream("/foo/conf/conf.txt");
printHelp(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void load2() throws IOException {
InputStream is = this.getClass().getResourceAsStream("../conf/conf.txt");
printHelp(is);
is.close();
}

public void load3() throws IOException {
InputStream is = this.getClass().getResourceAsStream("/conf/conf.txt");
printHelp(is);
is.close();
}

public static void printHelp(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}

到test目录:javac foo/ResourceLoader.java 然后 java foo.ResourceLoader得到结果如下:

c=d

e=f

e=f

总结:

1. 使用/开头的表示绝对路径,这个绝对路径其实是相对于classpath而言的,也就是classpath的目录+这个目录

上述java foo.ResourceLoader的classpath为 /home/test

2. 不使用/开头则表示相对路径,这个相对路径是相对于class文件本身而言的。

比如上述的ResourceLoader.class的路径是/home/test/fooInputStream is = this.getClass().getResourceAsStream("../conf/conf.txt");这里表示相对于该类所在目录的上一层的conf目录中获取conf.txt文件

         
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: