gpt4 book ai didi

java - 运行打包在jar文件中的exe

转载 作者:IT老高 更新时间:2023-10-28 20:38:40 25 4
gpt4 key购买 nike

我正在通过我的 java 程序执行一个 exe。路径是用 Java 硬编码的。

我已经将我的 exe 打包到了 jar 中。

但是因为我在 Java 文件中硬编码了路径名,所以我无法将我的 jar 作为独立程序执行。

包装此类 jar 的任何提示,即内部有一个 exe 并能够将其作为独立程序运行?

最佳答案

这会将 .exe 提取到本地磁盘上的本地文件中。当Java程序存在时,该文件将被删除。

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class Main
{
public static void main(final String[] args)
throws URISyntaxException,
ZipException,
IOException
{
final URI uri;
final URI exe;

uri = getJarURI();
exe = getFile(uri, "Main.class");
System.out.println(exe);
}

private static URI getJarURI()
throws URISyntaxException
{
final ProtectionDomain domain;
final CodeSource source;
final URL url;
final URI uri;

domain = Main.class.getProtectionDomain();
source = domain.getCodeSource();
url = source.getLocation();
uri = url.toURI();

return (uri);
}

private static URI getFile(final URI where,
final String fileName)
throws ZipException,
IOException
{
final File location;
final URI fileURI;

location = new File(where);

// not in a JAR, just return the path on disk
if(location.isDirectory())
{
fileURI = URI.create(where.toString() + fileName);
}
else
{
final ZipFile zipFile;

zipFile = new ZipFile(location);

try
{
fileURI = extract(zipFile, fileName);
}
finally
{
zipFile.close();
}
}

return (fileURI);
}

private static URI extract(final ZipFile zipFile,
final String fileName)
throws IOException
{
final File tempFile;
final ZipEntry entry;
final InputStream zipStream;
OutputStream fileStream;

tempFile = File.createTempFile(fileName, Long.toString(System.currentTimeMillis()));
tempFile.deleteOnExit();
entry = zipFile.getEntry(fileName);

if(entry == null)
{
throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName());
}

zipStream = zipFile.getInputStream(entry);
fileStream = null;

try
{
final byte[] buf;
int i;

fileStream = new FileOutputStream(tempFile);
buf = new byte[1024];
i = 0;

while((i = zipStream.read(buf)) != -1)
{
fileStream.write(buf, 0, i);
}
}
finally
{
close(zipStream);
close(fileStream);
}

return (tempFile.toURI());
}

private static void close(final Closeable stream)
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
}

关于java - 运行打包在jar文件中的exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com