本文共 3226 字,大约阅读时间需要 10 分钟。
(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包后,放到服务器上运行时,却报错,找不到配置文件。
[root@SearchEngine-TEST ~]# java -jar webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar file:/root/webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/resources/sharepointApp.xmlException 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.(FileInputStream.java:138) at java.io.FileInputStream. (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结构,对应配置文件存在。
[root@SearchEngine-TEST ~]# jar tf webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar。。。DownloadDemo.classMain.classMETA-INF/maven/cn.hadron/webservice/pom.propertiesMETA-INF/maven/cn.hadron/webservice/pom.xmlresources/a.xmlresources/result.xmlresources/sharepoint.xmlresources/sharepointApp.xmlresources/table.xmlTest.classMETA-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 ~]#
由上面运行jar包输出/root/webservice-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/resources/sharepointApp.xml
可知,该值是我们通过自定义方法readFile()读取的文件路径,显然这个值不是一般意义上的URL地址。所以jar包中的类源代码用File f=new File(项目内地址)
的形式,是不可能定位到文件资源的。
jar中资源有其专门的URL形式:jar:<url>!/{entry}
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"); }}
转载地址:http://whvab.baihongyu.com/