java io写入相对路径_java io的相对路径和绝对路径

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

例如:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png代码

packageio;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;publicclassInputStreamDemo {publicstaticvoidmain(String[] args)throwsIOException {

File root=newFile("");

System.out.println(root.getAbsolutePath());

File f=newFile("src/main/java/io/test.properties");

System.out.println(f.exists());

System.out.println(f.getAbsolutePath());

InputStream in=newFileInputStream("src/main/java/io/test.properties");byte[] b=newbyte[255];while(in.read(b)!=-1) {

System.out.println(newString(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就可以了。

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png代码

packageio;importjava.io.IOException;importjava.io.InputStream;publicclassResourceDemo {publicstaticvoidmain(String[] args)throwsIOException {

InputStream in=ResourceDemo.class.getResourceAsStream("test.properties");byte[] b=newbyte[255];while(in.read(b)!=-1) {

System.out.println(newString(b));

}

in.close();

}

}

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值