path 这个东西

刚毕业,感觉什么都是新的,可能我写的东西已经是老生常谈的东西了,如有不妥请大家指正.
前些天在公司学习richfaces,自己写小 demo 读文件的时候遇到了path 问题, 几经周折解决后,为了以后少犯这种错误,总结如下:
Java 中文件的读取大概有以下几种方式:
一, File f=new File(path);
二,InputStream myFileStream=this.getClass().getResourceAsStream();
三,InputStream myFileStream=this.getClass().getClassLoader()
.getResourceAsStream();

这里很容易混淆的是第二种和第三种方式,以例子为证:
为了表示的清楚,列举以下信息:
项目名称: test
项目目录: D:\workspace\test
测试类所在目录 D:\workspace\test\bin\com\tang\test\TestPath.java

package com.tang.test;

import java.io.File;

public class TestPath {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TestPath().showPath();
}

public void showPath() {
System.out.println("---------test group 1---------");
System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
System.out.println(TestPath.class.getClassLoader().getResource(""));
System.out.println(ClassLoader.getSystemResource(""));
System.out.println(this.getClass().getClassLoader().getResource(""));
System.out.println(this.getClass().getResource("/"));
System.out.println("---------test group 2---------");
System.out.println(this.getClass().getResource(""));
System.out.println("---------test group 3---------");
System.out.println(new File("").getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
}

}



输出:
---------test group 1---------
file:/D:/workspace/test/bin/
file:/D:/workspace/test/bin/
file:/D:/workspace/test/bin/
file:/D:/workspace/test/bin/
file:/D:/workspace/test/bin/
---------test group 2---------
file:/D:/workspace/test/bin/com/tang/test/
---------test group 3---------
D:\workspace\test
D:\workspace\test


总结:
注意到了吗,考虑第二种和第三种情况有getClassLoader()方法的返回的是 bin 目录下,否则返回的是类文件生成的目录下,即(bin/com/tang/tree/).
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值