Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java从jar中复制文件_Java_Jar_Resources_Stream_Zip - Fatal编程技术网

Java从jar中复制文件

Java从jar中复制文件,java,jar,resources,stream,zip,Java,Jar,Resources,Stream,Zip,我正试图将一个文件(Base.jar)复制到与正在运行的jar文件相同的目录中 我不断得到一个损坏的jar文件,当用winrar打开时,它仍然保持正确的类结构。我做错了什么?(我也尝试过不使用ZipInputStream,但没有帮助)字节[]是20480,因为这是它在磁盘上的大小 我的代码: private static void getBaseFile() throws IOException { InputStream input = Resource.class.getResou

我正试图将一个文件(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();
}

和处理异常

无需使用ZipInputStream,除非您希望将内容解压缩到内存中并读取。
只需使用BufferedInputStream(InputStream)或BufferedReader(InputStreamReader(InputStream))。

通过谷歌搜索发现:()对我有用吗

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)

ZipInputStream用于通过条目读取ZIP文件格式的文件。您需要复制整个文件(资源),也就是说,您只需复制InputStream中的所有字节,无论其格式如何。在Java 7中执行此操作的最佳方法是:

Files.copy(inputStream, targetPath, optionalCopyOptions);

有关详细信息,请参见API

您是否尝试过对文件进行逐字节比较?如果非要我猜的话,我怀疑你是在从文件末尾删减字节。我希望避免外部jarsBufferedInputStream没有改变任何东西
Files.copy(inputStream, targetPath, optionalCopyOptions);