java to jarfile_Java JarFile 解析

package com.github.binarylei;

import java.io.*;

import java.net.URL;

import java.net.URLDecoder;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

import java.util.jar.JarEntry;

import java.util.jar.JarFile;

/**

* @author: leigang

* @version: 2018-06-11

*/

public class JarFileUtils {

// 获取 clazz 所在 jar 包路径

public static String getJarPath(Class clazz) {

String filePath = null;

URL url = clazz.getProtectionDomain().getCodeSource().getLocation();

try {

// 转化为utf-8编码,支持中文

filePath = URLDecoder.decode(url.getPath(), "utf-8");

} catch (Exception e) {

e.printStackTrace();

}

File file = new File(filePath);

filePath = file.getAbsolutePath(); //得到windows下的正确路径

return filePath;

}

// 获取 clazz 所在 jar 包目录

public static String getJarDir(Class clazz) {

String jarPath = getJarPath(clazz);

if (jarPath.endsWith(".jar")) { // 可执行jar包运行的结果里包含".jar"

// 获取jar包所在目录

jarPath = jarPath.substring(0, jarPath.lastIndexOf("/") + 1);

}

return jarPath;

}

// 遍历 jar 包中的所有文件

public static List listJarFile(String path) throws IOException {

JarFile jarFile = new JarFile(path);

Enumeration entries = jarFile.entries();

ArrayList files = new ArrayList<>();

while (entries.hasMoreElements()) {

JarEntry jarEntry = entries.nextElement();

if (!jarEntry.isDirectory()) {

files.add("jar:file:/" + path + "!/" + jarEntry.getName());

}

}

return files;

}

// 遍历指定 jar 包目录中的文件

public static List listJarFile(String path, String dir) throws IOException {

if (!dir.endsWith("/")) {

dir += "/";

}

JarFile jarFile = new JarFile(path);

Enumeration entries = jarFile.entries();

ArrayList files = new ArrayList<>();

while (entries.hasMoreElements()) {

JarEntry jarEntry = entries.nextElement();

String filename = jarEntry.getName();

if (!jarEntry.isDirectory() && filename.startsWith(dir)) {

files.add("jar:file:/" + path + "!/" + filename);

}

}

return files;

}

// jar:file:/F:/test-1.0.0.jar!/dir/test.properties

public static void read(String jarFilePath) {

InputStream in = null;

try {

in = new URL(jarFilePath).openStream();

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String s="";

while((s=br.readLine()) != null)

System.out.println(s);

} catch (IOException e) {

e.printStackTrace();

} finally {

if (in != null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值