项目中一般都会遇到需要读取classpath下文件的问题,今天我打算把我知道的方式都整理一下,做一个记录方便以后查询,以下就是具体的方式:
// classpath目录下
URL resource = TestASM.class.getResource("/");
// classpath+该类所在路径
URL resource1 = TestASM.class.getResource("");
// classpath目录下
URL resource2 = TestASM.class.getClassLoader().getResource("");
// null
URL resource3 = TestASM.class.getClassLoader().getResource("/");
//file:/D:/sourceCode/demo4/target/classes/
System.out.println(resource);
//file:/D:/sourceCode/demo4/target/classes/com/example/demo4/asm/
System.out.println(resource1);
//file:/D:/sourceCode/demo4/target/classes/
System.out.println(resource2);
//null
System.out.println(resource3);
注意:如果TestASM.class.getResource("/")+fileName的方式来作为文件的路径,需要注意的是盘符前面的"/"需要去掉
// classpath下code.txt
InputStream asStream = TestASM.class.getClassLoader().getResourceAsStream("code.txt");
System.out.println(asStream);
// 加 / 表示获取classpath下code.txt,不加/返回为null
InputStream asStream1 = TestASM.class.getResourceAsStream("/code.txt");
System.out.println(asStream1);
// 获取classpath下code.txt文件
InputStream asStream2 = TestASM.class.getClassLoader().getSystemResourceAsStream("code.txt");
System.out.println(asStream2);
System.out.println("--------------------------------------");
// 使用工具类ResourceUtils获取classpath下文件
File file1 = ResourceUtils.getFile("classpath:code.txt");
FileInputStream is = new FileInputStream(file1);
System.out.println(is);
System.out.println("---------使用URL对象打开文件流,例子如下---------");
InputStream inputStream = TestASM.class.getResource("/code.txt").openStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\18030501\\Desktop\\aaa.txt");
byte[] bys = new byte[1024];
int len;
while ((len = inputStream.read(bys)) != -1) {
fos.write(bys, 0, len);
fos.flush();
}
inputStream.close();
fos.close();