Files
timi-io/src/main/java/com/imyeyu/io/JarReader.java
Timi 33177f5ded
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 40s
v0.0.3
2026-03-21 18:14:57 +08:00

84 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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));
}
}