1、遇到问题
(1)Maven项目开发阶段正常运行,Java程序可以读取配置文件
public class Main {
public static void main(String[] args) throws Exception {
Main.readFile("resources/sharepointApp.xml");
}
public static byte[] readFile(String fileName) throws Exception {
String path = SharepointApp.class.getClassLoader().getResource(fileName).getPath();
System.out.println(path);
File file = new File(path);
byte[] buf = new byte[(int) file.length()];
InputStream input=new FileInputStream(fileName);
input.read(buf);
input.close();
return buf;
}
}
(2)但是,Maven项目打成jar包后,放到服务器上运行时,却报错,找不到配置文件。
file:/root/webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/resources/sharepointApp.xml
Exception in thread "main" java.io.FileNotFoundException: file:/root/webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/resources/sharepointApp.xml (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.cntaiping.tpa.webservice.SharepointApp.readFile(SharepointApp.java:53)
at com.cntaiping.tpa.webservice.SharepointApp.sendSms(SharepointApp.java:30)
at Main.main(Main.java:22)
[root@SearchEngine-TEST ~]#```
(3)查看jar结构,对应配置文件存在。
。。。
DownloadDemo.class
Main.class
META-INF/maven/cn.hadron/webservice/pom.properties
META-INF/maven/cn.hadron/webservice/pom.xml
resources/a.xml
resources/result.xml
resources/sharepoint.xml
resources/sharepointApp.xml
resources/table.xml
Test.class
META-INF/maven/commons-io/
META-INF/maven/commons-codec/
META-INF/maven/commons-codec/commons-codec/
META-INF/maven/commons-io/commons-io/
META-INF/maven/commons-logging/
META-INF/maven/com.github.virtuald/
META-INF/maven/com.github.virtuald/curvesapi/
META-INF/maven/commons-logging/commons-logging/
[root@SearchEngine-TEST ~]#```
2、问题分析
由上面运行jar包输出/root/webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/resources/sharepointApp.xml可知,该值是我们通过自定义方法readFile()读取的文件路径,显然这个值不是一般意义上的URL地址。所以jar包中的类源代码用File f=new File(项目内地址)的形式,是不可能定位到文件资源的。
3、解决办法
jar中资源有其专门的URL形式:jar:<url>!/{entry}
可以通过Class类的getResourceAsStream()方法来获取资源文件输入流方式读取文件。
public class FileUtil {
/**
* 读取配置文件
* @return
*/
public static byte[] readConfigFile(String cfgFile) {
try {
InputStream in=FileUtil.class.getClassLoader().getResource(cfgFile).openStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
String line="";
while((line=br.readLine())!=null) {
sb.append(line);
}
return sb.toString().getBytes();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
//省略其他的方法
//主方法
public static void main(String[] args) throws IOException {
byte[] buf = FileUtil.readConfigFile("resources/sharepointApp.xml");
}
}