当前位置: 首页 > 知识库问答 >
问题:

如何使用InputStream从ZIP读取文件?

陈淳
2023-03-14

我必须使用SFTP从ZIP存档(只有一个文件,我知道它的名称)获取文件内容。我唯一拥有的是ZIP的InputStream。大多数示例显示了如何使用此语句获取内容:

ZipFile zipFile = new ZipFile("location");

但正如我所说,我的本地机器上没有ZIP文件,我不想下载它。输入流是否足以读取?

UPD:我就是这样做的:

import java.util.zip.ZipInputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTP {


    public static void main(String[] args) {

        String SFTPHOST = "host";
        int SFTPPORT = 3232;
        String SFTPUSER = "user";
        String SFTPPASS = "mypass";
        String SFTPWORKINGDIR = "/dir/work";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            ZipInputStream stream = new ZipInputStream(channelSftp.get("file.zip"));
            ZipEntry entry = zipStream.getNextEntry();
            System.out.println(entry.getName); //Yes, I got its name, now I need to get content
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            session.disconnect();
            channelSftp.disconnect();
            channel.disconnect();
        }


    }
}

共有3个答案

汪皓
2023-03-14

ZipInputStream本身就是一个InputStream,在每次调用getNextEntry()之后,它都会传递每个条目的内容。必须特别注意,不要关闭读取内容的流,因为它与ZIP流相同:

public void readZipStream(InputStream in) throws IOException {
    ZipInputStream zipIn = new ZipInputStream(in);
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        System.out.println(entry.getName());
        readContents(zipIn);
        zipIn.closeEntry();
    }
}

private void readContents(InputStream contentsIn) throws IOException {
    byte contents[] = new byte[4096];
    int direct;
    while ((direct = contentsIn.read(contents, 0, contents.length)) >= 0) {
        System.out.println("Read " + direct + "bytes content.");
    }
}

当将读取内容委托给其他逻辑时,可能需要使用FilterInputStream来包装ZipInputStream,以仅关闭条目,而不是整个流,如所示:

public void readZipStream(InputStream in) throws IOException {
    ZipInputStream zipIn = new ZipInputStream(in);
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        System.out.println(entry.getName());

        readContents(new FilterInputStream(zipIn) {
            @Override
            public void close() throws IOException {
                zipIn.closeEntry();
            }
        });
    }
}
宁欣怿
2023-03-14

我已经做到了:

 zipStream = new ZipInputStream(channelSftp.get("Port_Increment_201405261400_2251.zip"));
 zipStream.getNextEntry();

 sc = new Scanner(zipStream);
 while (sc.hasNextLine()) {
     System.out.println(sc.nextLine());
 }

它可以帮助我在不写入其他文件的情况下读取ZIP的内容。

林烨烨
2023-03-14

下面是一个关于如何提取ZIP文件的简单示例,您需要检查该文件是否是目录。但这是最简单的。

您缺少的步骤是读取输入流并将内容写入缓冲区,缓冲区将写入输出流。

// Expands the zip file passed as argument 1, into the
// directory provided in argument 2
public static void main(String args[]) throws Exception
{
    if(args.length != 2)
    {
        System.err.println("zipreader zipfile outputdir");
        return;
    }

    // create a buffer to improve copy performance later.
    byte[] buffer = new byte[2048];

    // open the zip file stream
    InputStream theFile = new FileInputStream(args[0]);
    ZipInputStream stream = new ZipInputStream(theFile);
    String outdir = args[1];

    try
    {

        // now iterate through each item in the stream. The get next
        // entry call will return a ZipEntry for each file in the
        // stream
        ZipEntry entry;
        while((entry = stream.getNextEntry())!=null)
        {
            String s = String.format("Entry: %s len %d added %TD",
                            entry.getName(), entry.getSize(),
                            new Date(entry.getTime()));
            System.out.println(s);

            // Once we get the entry from the stream, the stream is
            // positioned read to read the raw data, and we keep
            // reading until read returns 0 or less.
            String outpath = outdir + "/" + entry.getName();
            FileOutputStream output = null;
            try
            {
                output = new FileOutputStream(outpath);
                int len = 0;
                while ((len = stream.read(buffer)) > 0)
                {
                    output.write(buffer, 0, len);
                }
            }
            finally
            {
                // we must always close the output file
                if(output!=null) output.close();
            }
        }
    }
    finally
    {
        // we must always close the zip file.
        stream.close();
    }
}

代码摘录来自以下网站:

http://www.thecoderscorner.com/team-blog/java-and-jvm/12-reading-a-zip-file-from-java-using-zipinputstream#.U4RAxYamixR

 类似资料:
  • 问题内容: 我必须使用SFTP从ZIP存档(只有一个文件,我知道它的名称)中获取文件内容。我唯一拥有的是ZIP的。大多数示例说明如何使用以下语句获取内容: 但是正如我所说,我的本地计算机上没有ZIP文件,也不想下载它。是够看了? UPD: 这是我的方法: 问题答案: 好吧,我已经做到了: 它可以帮助我阅读ZIP的内容而无需写入另一个文件。

  • 问题内容: 我已经创建了可执行的jar文件(使用Eclipse),在jar中包含一组图像(.png)文件。所以我添加了一个源文件夹,其中所有图像都位于项目的文件夹中。代码必须访问这些文件才能使用创建BufferedImage 较早前,为了获得我使用的路径 在执行jar时,它抛出错误 URI不是分层的 所以现在我正在使用 但是如何使ImageIO从Inputstream读取?我试过如下 抛出错误 I

  • 问题内容: 我如何阅读像android app中的文本文件: 所以我可以返回一个字符串,如: 我想到的是(伪代码): 问题答案: 试试这个

  • 我想从嵌套的zip文件中读取(另一个zip中的zip文件) a.zip->b.zip->c.txt 以下是测试程序: 和输出:

  • 问题内容: 我从SUN网站(http://java.sun.com/developer/technicalArticles/Programming/compression/)找到了示例,但是它返回BufferedOutputStream。但是我想将ZipEntry文件作为InputStream,然后处理下一个文件。那可能吗?我的程序无法访问硬盘,因此它甚至无法临时保存文件。 问题答案: 好吧,只需

  • 问题内容: 在一个项目上,我通过一个类似于控制台的小窗口运行Java应用程序。由于这里有一个很棒的社区,我设法通过从流程输出数据来解决问题,但是由于没有输入流,我运行的命令行应用程序将不断出错。 基于该线程中最后一个有用的答复,我想我将以类似的方式实现该实现,但是在javadocs中以及整个google和互联网中寻找某个类,该类确实没有发现任何解释方法。 因此,我需要一些链接,示例,教程,示例代码