java 项目打成jar包后,读取 src/resources/
2021-08-25 本文已影响0人
愤怒的阿昆达
背景:
java要调用js引擎,执行js。
然后,我需要外引js文件。
我要用java去读取这个js文件。
-
在开发时(本地debug运行),我把js文件放在src根目录下,直接读。
image.png
readFile("src/turf-@6-abridged.js");
public static String readFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
- 在用maven打成jar,部署到linux上使用java -jar启动后报错,找不到路径。
解决
-
把js挪到src/resources/下一份
image.png
- 读取:
public class GismapProviderManage {
private String getTurfJsLinux(){
String turfJsPath = "/turf-@6-abridged.js";
// 用类装载器读取jar中的文件。利用this.getClass().getResourceAsStream方法,以流的形式拿到Jar包中的文件。
BufferedReader in = null;
try{
in = new BufferedReader(new InputStreamReader(new GismapProviderManage().getClass().getResourceAsStream(turfJsPath)));
StringBuffer buffer = new StringBuffer();
String line = "";
while (true){
try {
if (!((line = in.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
}
String input = buffer.toString();
return input;
}catch (Exception e){
e.printStackTrace();
log.error("异常!读取 turf-@6-abridged.js 文件失败!");
return null;
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}