84 lines
1.7 KiB
Java
84 lines
1.7 KiB
Java
package com.imyeyu.io;
|
||
|
||
import lombok.Getter;
|
||
|
||
import java.io.File;
|
||
import java.io.FileNotFoundException;
|
||
import java.io.IOException;
|
||
import java.io.InputStream;
|
||
import java.util.Enumeration;
|
||
import java.util.HashMap;
|
||
import java.util.Map;
|
||
import java.util.jar.JarEntry;
|
||
import java.util.jar.JarFile;
|
||
|
||
/**
|
||
* Jar 文件读取
|
||
*
|
||
* @author 夜雨
|
||
* @version 2021-12-01 17:39
|
||
*/
|
||
@Getter
|
||
public class JarReader extends JarFile {
|
||
|
||
/** jar 所有文件的数据流映射列表,Map<路径, 数据流> */
|
||
private final Map<String, InputStream> files;
|
||
|
||
/**
|
||
* 默认构造
|
||
*
|
||
* @param file 文件
|
||
* @throws IOException 读取异常
|
||
*/
|
||
public JarReader(File file) throws IOException {
|
||
super(file);
|
||
|
||
files = new HashMap<>();
|
||
|
||
Enumeration<JarEntry> entries = entries();
|
||
while (entries.hasMoreElements()) {
|
||
JarEntry entry = entries.nextElement();
|
||
if (entry != null && !entry.isDirectory()) {
|
||
files.put(entry.getName(), getInputStream(entry));
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 该文件是否存在
|
||
*
|
||
* @param path 路径
|
||
* @return true 为存在
|
||
*/
|
||
public boolean has(String path) {
|
||
return files.containsKey(path);
|
||
}
|
||
|
||
/**
|
||
* 获取文件输入流
|
||
*
|
||
* @param path 路径
|
||
* @return 输入流
|
||
* @throws FileNotFoundException 文件不存在
|
||
*/
|
||
public InputStream getInputStream(String path) throws FileNotFoundException {
|
||
if (has(path)) {
|
||
return files.get(path);
|
||
} else {
|
||
throw new FileNotFoundException("Not found file: " + path);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取某文件为字节数据
|
||
*
|
||
* @param path 路径
|
||
* @return 字节数据
|
||
* @throws FileNotFoundException 文件不存在
|
||
*/
|
||
public byte[] getBytes(String path) throws IOException {
|
||
return IO.toBytes(getInputStream(path));
|
||
}
|
||
|
||
}
|