如果需要拷贝jar包中的目录及各个子文件夹时,用getResourceAsStream(name)是无法做到的。该方法只能加载一个文件,此时只能通过以下代码来获取jar包的绝对路径this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
在获得jar包之后,将其解压即可。
String classPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
File jarFile = new File(classPath);
File destDirectory =new File(serverModuleSrcPackages.append(File.separator).toString());
FileUtils.uncompress(jarFile,destDirectory,"server_java/");
``
解压代码:
/**
* 解压Jar文件
* @param jarFile 指定jar文件
* @param tarDir 指定解压文件夹
* @throws IOException 抛出异常
* @param includePath:要拷贝的前缀,过滤不需要的文件
* @throws IOException
*/
public static void uncompress(File jarFile, File tarDir,String includePath) throws IOException {
JarFile jfInst = new JarFile(jarFile);
Enumeration<JarEntry> enumEntry = jfInst.entries();
while (enumEntry.hasMoreElements()) {
JarEntry jarEntry = enumEntry.nextElement();
//构造解压文件实体
if(!jarEntry.getName().contains(includePath)){
continue;
}
File tarFile = new File(tarDir, jarEntry.getName().replace(includePath,""));
//创建文件
makeFile(jarEntry, tarFile);
if (jarEntry.isDirectory()) {
continue;
}
//构造输出流
FileChannel fileChannel = new FileOutputStream(tarFile).getChannel();
//取输入流
InputStream ins = jfInst.getInputStream(jarEntry);
transferStream(ins, fileChannel);
}
}
/**
* 流交换
* @param ins 输入流
* @param targetChannel 输出流
*/
private static void transferStream(InputStream ins, FileChannel targetChannel) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 10);
ReadableByteChannel rbcInst = Channels.newChannel(ins);
try {
while (-1 != (rbcInst.read(byteBuffer))) {
byteBuffer.flip();
targetChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (null != rbcInst) {
try {
rbcInst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != targetChannel) {
try {
targetChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 创建文件
* @param jarEntry jar实体
* @param fileInst 文件实体
* @throws IOException 抛出异常
*/
public static void makeFile(JarEntry jarEntry, File fileInst) {
if (!fileInst.exists()) {
if (jarEntry.isDirectory()) {
fileInst.mkdirs();
} else {
try {
fileInst.createNewFile();
} catch (IOException e) {
System.out.println("创建文件失败>>".concat(fileInst.getPath()));
}
}
}
}