How to read file from ZIP using InputStream?

后端 未结 7 861
旧巷少年郎
旧巷少年郎 2020-11-29 09:11

I must get file content from ZIP archive (only one file, I know its name) using SFTP. The only thing I\'m having is ZIP\'s InputStream. Most examples show how g

7条回答
  •  半阙折子戏
    2020-11-29 09:37

    Below is a simple example on how to extract a ZIP File, you will need to check if the file is a directory. But this is the simplest.

    The step you are missing is reading the input stream and writing the contents to a buffer which is written to an output stream.

    // 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();
        }
    }
    

    Code excerpt came from the following site:

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

提交回复
热议问题