java io的相对路径和绝对路径

简单的说,在使用inputstream读取文件的时候,所谓的相对路径是相对于工程目录的,绝对路径当然是对于盘符根目录来说。

例如:

 

代码
package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {
public static void main(String[] args) throws IOException {
File root
= new File("");
System.out.println(root.getAbsolutePath());
File f
= new File("src/main/java/io/test.properties");
System.out.println(f.exists());
System.out.println(f.getAbsolutePath());
InputStream in
= new FileInputStream("src/main/java/io/test.properties");
byte[] b = new byte[255];
while(in.read(b) != -1) {
System.out.println(
new String(b));
}
}
}

 

输出结果:

 

E:\EclipseProjects\demoSet
true
E:\EclipseProjects\demoSet\src\main\java\io\test.properties
tt = "good"

E:\EclipseProjects\demoSet

true

E:\EclipseProjects\demoSet\src\main\java\io\test.properties

tt = "good"

 

我只是在和该类同级的地方放了一个test.properties,里面写了tt="good",用相对路径的话只能把目录写全,我本来以为直接写test.properties就可以了。

 

还有一种方法是直接从类路径中读取

 

代码
package io;

import java.io.IOException;
import java.io.InputStream;

public class ResourceDemo {
public static void main(String[] args) throws IOException {
InputStream in
= ResourceDemo.class.getResourceAsStream("test.properties");
byte[] b = new byte[255];
while (in.read(b) != -1) {
System.out.println(
new String(b));
}
in.close();
}
}

 

使用getResourceAsStream方法的相对路径就在该类的目录下,而写上路径"/test.properties"系统就会到classpath的根目录底下去寻找。

相比较而言,getResourceAsStream方法更好更ok,推荐使用

 

 

 

posted @ 2009-12-10 00:20  雪霁霜飞  阅读(2690)  评论(0编辑  收藏  举报