一般有将java项目打成jar包来执行, 有可能需要读取一些额外的文件, 若想将文件打入jar包中, 此时的jar包就是一个文件了, 采取一般的读取文件获取方式就会失败
可以采用
InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("etc/core.txt");
返回流的方式,(一般的配置文件放置的位置)
ClassLoader.getSystemResource("").getPath()获取当前目录 打成jar包时会失败
import java.io.*;
public class demo2 {
public static void main(String[] args) throws IOException {
System.out.println("#System.getProperty(\"user.dir\") 获取当前目录: ");
System.out.println(" "+System.getProperty("user.dir"));
System.out.println("#demo2.class.getResource(\"\").getPath() 获取当前目录: ");
System.out.println(" "+demo2.class.getResource("").getPath());
System.out.println("#Thread.currentThread().getContextClassLoader().getResource(\"\").getPath() 获取当前目录: ");
System.out.println(" 打成jar包获取不到");
//System.out.println(" " +Thread.currentThread().getContextClassLoader().getResource("").getPath());
System.out.println("#ClassLoader.getSystemResource(\"\").getPath() 获取当前目录: ");
System.out.println(" 打成jar包获取不到");
//System.out.println(" "+ClassLoader.getSystemResource("").getPath());
System.out.println("===========使用流方式(ClassLoader.getSystemClassLoader().getResourceAsStream(\"etc/core.txt\"))读取jar内的文件================");
InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("etc/core.txt");
System.out.println("返回文件中的字符数(一个汉字为3),available: "+is.available());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
System.out.println(bufferedReader.readLine());
System.out.println(bufferedReader.readLine());
System.out.println(bufferedReader.readLine());
}
}
idea设置resource目录类型
maven打包的设置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo2</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<!-- 此处为程序主入口-->
<mainClass>com.example.demo2</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>