JAVA读取jar包内部配置文件
Java实现从jar包中读取指定文件的方法

Java实现从jar包中读取指定⽂件的⽅法本⽂实例讲述了Java实现从jar包中读取指定⽂件的⽅法。
分享给⼤家供⼤家参考,具体如下:以下的Java代码实现了从⼀个jar包中读取指定⽂件的功能:/*** This class implements the funcationality of reading and writing files in jar files.*/package com.leo.util;import java.io.InputStream;import java.io.FileOutputStream;import java.util.jar.*;import java.util.Enumeration;/*** @author Leo Share* @since 08/09/2007* @version 1.0*/public class JarFileAccess {private static final String fileSeparator = System.getProperty("file.separator");public void accessJarFile(String jarFileName, String fromDir, String toDir) throws Exception{JarFile myJarFile = new JarFile(fromDir+fileSeparator+jarFileName);Enumeration myEnum = myJarFile.entries();while(myEnum.hasMoreElements()){JarEntry myJarEntry = (JarEntry)myEnum.nextElement();if(myJarEntry.getName().equals("jbossall-client.jar")){InputStream is = myJarFile.getInputStream(myJarEntry);FileOutputStream fos = new FileOutputStream(toDir+fileSeparator+myJarEntry.getName());byte[] b = new byte[1024];int len;while((len = is.read(b))!= -1){fos.write(b, 0, len);}fos.close();is.close();break;} else{continue;}}myJarFile.close();}}更多关于java算法相关内容感兴趣的读者可查看本站专题:《》、《》、《》和《》希望本⽂所述对⼤家java程序设计有所帮助。
解决SpringBootjar包中的文件读取问题

解决SpringBootjar包中的⽂件读取问题前⾔SpringBoot微服务已成为业界主流,从开发到部署都⾮常省时省⼒,但是最近⼩明开发时遇到⼀个问题:在代码中读取资源⽂件(⽐如word⽂档、导出模版等),本地开发时可以正常读取,但是,当我们打成jar包发布到服务器后,再次执⾏程序时就会抛出找不到⽂件的异常。
背景这个问题是在⼀次使⽤freemarker模版引擎导出word报告时发现的。
⼤概说⼀下docx导出java实现思路:导出word的⽂档格式为docx,事先准备好⼀个排好版的docx⽂档作为模版,读取解析该模版,将其中的静态资源替换再导出。
docx⽂档本⾝其实是⼀个压缩的zip⽂件,将其解压过后就会发现它有⾃⼰的⽬录结构。
问题这个docx⽂档所在⽬录如下图所⽰:在本地调试时,我使⽤如下⽅式读取:import org.springframework.util.ResourceUtils;public static void main(String[] args) throws IOException {File docxTemplate = ResourceUtils.getFile("classpath:templates/docxTemplate.docx");}可以正常解析使⽤,但是打包发布到beta环境却不可⽤。
抛出异常如下:java.io.FileNotFoundException: class path resource [templates/docxTemplate.docx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/usr/local/subject-server.jar!/BOOT-INF/classes!/templates/docxTe显⽽易见,这个异常告诉我们:没有找到⽂件,但是将jar包解压过后,发现这个⽂件是真真实实存在的。
java解析jar文件,读取并进行调用

java解析jar⽂件,读取并进⾏调⽤简单介绍了如何使⽤java.util.jar包提供的API操作jar⽂件,下⾯通过⼀个相对复杂的例⼦讲述⼀些Jar⽂件相关的⾼级应⽤。
仔细读读这篇⽂章并参考⼀下相关的java doc会对你学习java语⾔有很⼤的帮助。
下⾯的应⽤程序将实现从http服务器装载并执⾏⼀个jar⽂件的功能,⽐如你的Jar⽂件的地址为。
要实现这个功能我们应该⾸先建⽴与这个⽂件的连接然后通过MANIFEST的信息描述得到Main-Class的值,最后装载并运⾏这个class。
这⾥⾯需要⽤到和反射的⼀些重要知识。
这个应⽤程序由两个类组成:JarClassLoader和JarRunner。
JarClassLoader扩展了URLClassLoader,它有⼀个成员为URL类型的url变量。
public JarClassLoader(URL url){super(new URL[] { url });this.url = url;}它的两个重要⽅法是getMainClassName()和invokeClass(),其中前者的⽬的是通过URL和jar取得连接后,读取MANIFEST的Main-Class属性从⽽得到应⽤程序的⼊点,这⾮常重要。
得到⼊点后我们就可以通过反射机制装载和运⾏得到的主类。
public String getMainClassName() throws IOException {URL u = new URL("jar", "", url + "!/");JarURLConnection uc = (JarURLConnection)u.openConnection();Attributes attr = uc.getMainAttributes();return attr != nullattr.getValue(.MAIN_CLASS): null;}public void invokeClass(String name, String[] args)throws ClassNotFoundException,NoSuchMethodException,InvocationTargetException{Class c = this.loadClass(name);Method m = c.getMethod("main", new Class[] { args.getClass() });m.setAccessible(true);int mods = m.getModifiers();if (m.getReturnType() != void.class || !Modifier.isStatic(mods) ||!Modifier.isPublic(mods)) {throw new NoSuchMethodException("main");}try {m.invoke(null, new Object[] { args });} catch (IllegalAccessException e) {// This should not happen, as we have disabled access checks}}URL u = new URL("jar", "", url + "!/");JarURLConnection uc = (JarURLConnection)u.openConnection();这两段代码构造⼀个JarURLConnection的实例,注意!/的分隔符的意思是这个url表⽰的是整个jar⽂件。
java打jar包的几种方式详解

java打jar包的⼏种⽅式详解⼀、制作只含有字节码⽂件的jar包我们先来看只含有字节码⽂件,即只含有class⽂件的jar包怎么制作,这是最简单的形式1、最简单的jar包——直接输出hello最终⽣成的jar包结构META-INFHello.class⽅法步骤(1)⽤记事本写⼀个Hello.java的⽂件class Hello{public static void main(String[] agrs){System.out.println("hello");}}(2)⽤命令⾏进⼊到该⽬录下,编译这个⽂件 javac Hello.java(3)将编译后的Hello.class⽂件打成jar包 jar -cvf hello.jar Hello.class c表⽰要创建⼀个新的jar包,v表⽰创建的过程中在控制台输出创建过程的⼀些信息,f表⽰给⽣成的jar包命名(4)运⾏jar包 java -jar hello.jar 这时会报如下错误 hello.jar中没有主清单属性 添加Main-Class属性 ⽤压缩软件打开hello.jar,会发现⾥⾯多了⼀个META-INF⽂件夹,⾥⾯有⼀个MENIFEST.MF的⽂件,⽤记事本打开Manifest-Version: 1.0Created-By: 1.8.0_121 (Oracle Corporation) 在第三⾏的位置写⼊ Main-Class: Hello (注意冒号后⾯有⼀个空格,整个⽂件最后有⼀⾏空⾏),保存 再次运⾏ java -jar hello.jar ,此时成功在控制台看到 hello ,成功2、含有两个类的jar包——通过调⽤输出hello最终⽣成的jar包结构META-INFTom.classHello.class⽅法步骤(1)⽤记事本写⼀个Hello.java和⼀个Tom.java的⽂件 ⽬的是让Hello调⽤Tom的speak⽅法class Hello{public static void main(String[] agrs){Tom.speak();}}class Tom{public static void speak(){System.out.println("hello");}}(2)编译: javac Hello.java 此时Hello.java和Tom.java同时被编译,因为Hello中调⽤了Tom,在编译Hello的过程中发现还需要编译Tom(3)打jar包,这次我们换⼀种⽅式直接定义Main-Class。
java获取配置文件的参数的方法

一、概述Java是一种流行的编程语言,广泛应用于企业级软件开发。
在Java应用程序中,经常需要读取配置文件中的参数,以便程序在不同环境下能够灵活运行。
本文将介绍在Java中获取配置文件参数的方法。
二、使用Properties类在Java中,可以使用Properties类来读取配置文件。
Properties是HashTable的子类,它用于处理键值对形式的配置信息。
下面是使用Properties类获取配置文件参数的步骤:1. 创建Properties对象首先使用Properties类创建一个对象,用于存储配置文件中的参数。
可以通过以下代码实现:```javaProperties props = new Properties();```2. 加载配置文件接下来,需要将配置文件加载到Properties对象中。
通常配置文件的格式是.properties,可以通过以下代码加载:```javatry{InputStream inputStream =getClass().getClassLoader().getResourceAsStream("config.prope rties");props.load(inputStream);}catch(IOException e){e.printStackTrace();}```上述代码中,使用ClassLoader的getResourceAsStream方法加载配置文件,并使用Properties的load方法将文件内容加载到props 对象中。
3. 获取参数值一旦配置文件加载到props对象中,就可以通过getProperty方法获取参数值。
获取名为"db.url"的参数值可以使用以下代码:```javaString dbUrl = props.getProperty("db.url");```通过上述步骤,就可以在Java中轻松获取配置文件中的参数值了。
打jar包之后读不到properties文件

打jar包之后读不到properties⽂件(1)在Spring项⽬中有专门读取properties⽂件的类代码如下:import org.springframework.core.io.support.PropertiesLoaderUtils;Properties ret = PropertiesLoaderUtils.loadProperties(new ClassPathResource("XXX.properties"));rs = ret.getProperty("proname");(2)在普通项⽬中读取properties⽂件Properties properties = new Properties();InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");properties.load(in);String str = properties.getProperty("name");遇到的问题是项⽬打成jar包后⽆法读取到jar包内的properties⽂件发现在eclipse⾥⼀切正常,但打成jar包后就⽆法读取到properties⽂件了。
之前的程序是这样获取配置⽂件的:Thread.currentThread().getContextClassLoader().getResource("").getPath() +filename+".properties")来获取properties⽂件,但发现⼀运⾏就报错.后来将代码改成:this.getClass().getClassLoader().getResourceAsStream(filename+".properties")⼀切正常~关于java 的 classloader 还是有点概念不清,需要补补~~⼀般在项⽬中使⽤properties配置⽂件的时候都将相关的properties⽂件放在src⽬录下,在将该app打包⽣成jar后,相应的properties配置⽂件⽣成在jar包中,这样的话要修改配置⽂件⼜要重新打jar包,那是相当的⿇烦。
java读JAR包里的配置文件

private static String getXmlContent()throws IOException {Reader f = newInputStreamReader(QueryWeather.class.getClass().getResourceAsStream("/weather/we ather.xml"));BufferedReader fb = new BufferedReader(f);StringBuffer sb = new StringBuffer(“”);String s = "";while((s = fb.readLine()) != null) {sb = sb.append(s);}return sb.toString();}package com.read;import java.io.*;public class Resource {public void getResource() throws IOException{//返回读取指定资源的输入流InputStream is=this.getClass().getResourceAsStream("/struts-default.xml"); BufferedReader br=new BufferedReader(new InputStreamReader(is));String s="";while((s=br.readLine())!=null)System.out.println(s);}}这个类是jar包中的类,同时jar根下还有个struts-default.xml文件。
ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream("com/xxx/xxxx/yourfile.xml");一般情况下properties文件都是在工程内使用的,如果application打成jar包之后,修改properties文件后就需要重新打jar,很麻烦。
调用jar包外配置文件

项目中,经常把一部分功能独立出来,做一个java project,然后打成jar包供其他项目引用。
这时候,如果jar包中需要读取配置文件信息,则很少把该配置打进jar包,因为它不方便修改,更多都是采用jar包读取外部配置文件。
案例:项目工程名:auth -- 很明显,做鉴权使用的项目配置文件:init.properties log4j.properties项目引用jar包:lib/servlet-api.jarlib/log4j-1.2.15.jarlib/commons-collections-3.1.jarlib/commons-logging-1.0.4.jarlib/commons-pool.jarlib/ojdbc14.jar读取配置文件示例:目录结构如下:解决方案I:自定义manifest.mf 文件解释:Manifest-Version: 1.0 版本号,没啥特殊含义,但一定要有;Class-Path: 所有引用的jar包注意:每个“:”后面都要加空格,Class-Path中每个jar包间也加空格最后一行为空行截图如下:b.通过Eclipse 到处jar包右键项目工程----Export -- 选择Java下JAR File,下一步件外部读取),选择导出jar包的位置;注意:右侧的.classpath这些都不要选中,只把src下的java文件打包。
下一步下一步:选中自定义的manifest.mf文件,完成测试:新建项目,导入刚刚生成的jar包和jar需要的所有包(把jar包所在工程lib下所有引用jar拿过来),在src下写入配置文件,目录结构如下:测试:测试结果:这就是方案1,总结:自定义manifest.mf 文件,配置清楚jar所需要的所有lib。
当其他系统引用该jar时,相当于把包拉到系统中(jar的内容相当于系统自定义的),它读取的配置文件就是从系统的classpath下读取。