Java 从当前运行的jar中提取jar
我试图从当前运行的jar中提取2个jar文件,但是它们总是以2kb结束,即使它们的大小是104kb和1.7m,这就是我得到的Java 从当前运行的jar中提取jar,java,jar,extract,Java,Jar,Extract,我试图从当前运行的jar中提取2个jar文件,但是它们总是以2kb结束,即使它们的大小是104kb和1.7m,这就是我得到的 public static boolean extractFromJar(String fileName, String dest) { if (Configuration.getRunningJarPath() == null) { return false; } File file = new File(dest + fileN
public static boolean extractFromJar(String fileName, String dest) {
if (Configuration.getRunningJarPath() == null) {
return false;
}
File file = new File(dest + fileName);
if (file.exists()) {
return false;
}
if (file.isDirectory()) {
file.mkdir();
return false;
}
try {
JarFile jar = new JarFile(Configuration.getRunningJarPath());
Enumeration<JarEntry> e = jar.entries();
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
InputStream in = new BufferedInputStream(jar.getInputStream(je));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(file));
copyInputStream(in, out);
}
return true;
} catch (Exception e) {
Methods.debug(e);
return false;
}
}
private final static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
while (in.available() > 0) {
out.write(in.read());
}
out.flush();
out.close();
in.close();
}
publicstaticbooleanextractfromjar(stringfilename,stringdest){
if(Configuration.getRunningJarPath()==null){
返回false;
}
文件文件=新文件(dest+文件名);
if(file.exists()){
返回false;
}
if(file.isDirectory()){
mkdir()文件;
返回false;
}
试一试{
JarFile jar=newjarfile(Configuration.getRunningJarPath());
枚举e=jar.entries();
而(e.hasMoreElements()){
JarEntry je=e.nextElement();
InputStream in=new BufferedInputStream(jar.getInputStream(je));
OutputStream out=新的BufferedOutputStream(
新文件输出流(文件));
copyInputStream(输入、输出);
}
返回true;
}捕获(例外e){
方法:调试(e);
返回false;
}
}
私有最终静态无效copyInputStream(InputStream输入,OutputStream输出)
抛出IOException{
while(in.available()>0){
out.write(in.read());
}
out.flush();
out.close();
in.close();
}
我不确定如何提取jar,但每个jar实际上都是一个zip文件,所以您可以尝试解压缩它
您可以在此处找到有关在java中解压的信息:
这应该比依赖InputStream更好。available()方法:
available()
方法读取数据不可靠,因为根据其文档,它只是一个估计值。在读取非ve之前,您需要依赖
read()
方法
byte[] contentBytes = new byte[ 4096 ];
int bytesRead = -1;
while ( ( bytesRead = inputStream.read( contentBytes ) ) > 0 )
{
out.write( contentBytes, 0, bytesRead );
} // while available
您可以讨论available()
的问题所在
byte[] contentBytes = new byte[ 4096 ];
int bytesRead = -1;
while ( ( bytesRead = inputStream.read( contentBytes ) ) > 0 )
{
out.write( contentBytes, 0, bytesRead );
} // while available