Распаковать содержимое из заархивированного файла в память [дубликат]

Только для debug / dev я публикую это, если он кому-то полезен

Интересные вещи, в Firebug (и, возможно, другие консоли js), ничего не происходит после входа в игру, только после того, как указанная продолжительность сна (...)

function sleepFor( sleepDuration ){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
}

Пример использования:

function sleepThenAct(){ sleepFor(2000); console.log("hello js sleep !"); }
17
задан Tony 18 June 2015 в 13:57
поделиться

3 ответа

Ну, я сделал это:

 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 без записи в другой файл.

14
ответ дан Tony 24 August 2018 в 10:04
поделиться

Ниже приведен простой пример того, как извлечь 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

15
ответ дан Freedom_Ben 24 August 2018 в 10:04
поделиться

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.");
    }
}

При делегировании содержимого чтения на другую логику это может быть необходимо для обертывания ZipInputStream с помощью FilterInputStream, чтобы закрыть только запись вместо всего потока, как в:

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();
            }
        });
    }
}
2
ответ дан haui 24 August 2018 в 10:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: