【问题标题】:Java copying a file out of a jarJava从jar中复制文件
【发布时间】:2013-07-04 03:35:00
【问题描述】:

我正在尝试将文件 (Base.jar) 复制到与正在运行的 jar 文件相同的目录 我不断得到一个损坏的 jar 文件,当用 winrar 打开时,它仍然保持正确的类结构。我究竟做错了什么? (我也尝试过不使用 ZipInputStream,但这没有帮助)字节 [] 是 20480,因为这是它在磁盘上的大小。

我的代码:

private static void getBaseFile() throws IOException 
{
    InputStream input = Resource.class.getResourceAsStream("Base.jar");
    ZipInputStream zis = new ZipInputStream(input);
    byte[] b = new byte[20480];
    try {
        zis.read(b);
    } catch (IOException e) {
    }
    File dest = new File("Base.jar");
    FileOutputStream fos = new FileOutputStream(dest);
    fos.write(b);
    fos.close();
    input.close();
}

【问题讨论】:

  • 您是否尝试过逐字节比较文件?如果我不得不猜测,我怀疑您正在从文件末尾修剪字节。

标签: java jar resources stream zip


【解决方案1】:
InputStream input = Resource.class.getResourceAsStream("Base.jar");

File fileOut = new File("your lib path");

OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();

并处理异常

【讨论】:

  • 我希望避免使用外部 jars
【解决方案2】:

不需要使用 ZipInputStream,除非你想将内容解压到内存中并读取。 只需使用 BufferedInputStream(InputStream) 或 BufferedReader(InputStreamReader(InputStream))。

【讨论】:

  • BufferedInputStream 没有改变任何东西
【解决方案3】:

更多谷歌搜索是否发现了这个:(Convert InputStream to byte array in Java) 为我工作

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, nRead);
}
buffer.flush(); 
return buffer.toByteArray();

(它看起来与 IOUtils.copy() 的 src 非常相似)

【讨论】:

    【解决方案4】:

    ZipInputStream 用于按条目读取 ZIP 文件格式的文件。您需要复制整个文件(资源),无论格式是什么,您都需要简单地从 InputStream 复制所有字节。在 Java 7 中最好的方法是:

    Files.copy(inputStream, targetPath, optionalCopyOptions);
    

    详见 API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2010-11-26
      • 2013-08-26
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多