现在的位置: 首页 > 综合 > 正文

java读取jar包内的文件

2013年02月28日 ⁄ 综合 ⁄ 共 1225字 ⁄ 字号 评论关闭

读取jar包内的资源主要有class和classloader的getResourceAsStream方法,工程结构如下:

package dong.sun;
import java.io.InputStream;

public class LoadFile {
public static void main(String[] args) { 
  InputStream is = getPerspectiveIcon();
  if (is != null) {
	  System.out.println("Loading the File successfully");
  }
}

public static InputStream getPerspectiveIcon() {
	return LoadFile.class.getResourceAsStream("/ui/images/APP.png");
//	return LoadFile.class.getClassLoader().getResourceAsStream("ui/images/APP.png"); //这两种方法都可以
} 
} 

pom:

<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>test</groupId>
  <artifactId>FileInJar</artifactId>
  <version>1.0</version>
  <name>FileInJar</name>
  <description>FileInJar</description>
  <build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-jar-plugin</artifactId>
			<configuration>
			<archive>
			<addMavenDescriptor>false</addMavenDescriptor> <!-- set to true will embed pom.xml into META-INF-->
			<manifest>
			<mainClass>dong.sun.LoadFile</mainClass>
			</manifest>
			</archive>
			</configuration>
		</plugin>
	</plugins>
</build>
</project>

ps:

这篇文章讲的比较全面http://hxraid.iteye.com/blog/483115

抱歉!评论已关闭.