简单的说,在使用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

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,推荐使用

 

 

 

相关文章:

猜你喜欢
  • 2022-01-03
  • 2022-03-07
  • 2022-03-08
  • 2021-09-21
  • 2021-05-11
相关资源
相似解决方案