Invalid stored block lengths ошибка как исправить

I am trying to extract a ZIP file from my current JAR using:

InputStream resource = getClass().getClassLoader().getResourceAsStream(name);

This get the correct InputStream, but it gives an error when I try to unzip it using the following code (I’m storing each file into a Hashmap<file, filename>):

public static HashMap<String, String> readZip(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    HashMap<String, String> list = new HashMap<>();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
        if (!entry.isDirectory()) {
            StringBuilder stringBuilder = new StringBuilder();
            while (IOUtils.read(zipInputStream, buffer) > 0) {
                stringBuilder.append(new String(buffer, "UTF-8"));
            }
            list.put(stringBuilder.toString(), entry.getName());
        }
        zipInputStream.closeEntry();
        entry = zipInputStream.getNextEntry();
    }
    zipInputStream.closeEntry();
    zipInputStream.close();
    return list;
}

However when I try to do this, I get this exception (on IOUtils.read)

java.util.zip.ZipException: invalid stored block lengths
   at java.util.zip.InflaterInputStream.read(Unknown Source)
   at java.util.zip.ZipInputStream.read(Unknown Source)

Am I doing this wrong? I’ve done plenty of googling of the error, and I didn’t see anything related to my issue.

I’m not really sure what to do here, except that zip contains a header that you have to seek beyond before you can start your inflate stream

var fs = require('fs');
var zlib = require('zlib');

var file = process.argv[2];

var zs = zlib.createInflateRaw();
var fstream = fs.createReadStream(file);

function doIt() {
  if (fstream.read(2))
    fstream.pipe(zs);
  else
    setImmediate(doIt);
}

setImmediate(doIt);

zs.on('error', function(err) {
  console.error(err.errno, err);
});

And it works fine. Closing as this is mostly beyond the scope of node, if you can find a more minimal test case that can show a problem with our usage of zlib please let us know.

Я пытаюсь извлечь ZIP файл из моего текущего JAR, используя:

InputStream resource = getClass().getClassLoader().getResourceAsStream(name);

Получите правильный InputStream, но он дает ошибку, когда я пытаюсь разархивировать его, используя следующий код (я храню каждый файл в Hashmap<file, filename>):

public static HashMap<String, String> readZip(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    HashMap<String, String> list = new HashMap<>();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
        if (!entry.isDirectory()) {
            StringBuilder stringBuilder = new StringBuilder();
            while (IOUtils.read(zipInputStream, buffer) > 0) {
                stringBuilder.append(new String(buffer, "UTF-8"));
            }
            list.put(stringBuilder.toString(), entry.getName());
        }
        zipInputStream.closeEntry();
        entry = zipInputStream.getNextEntry();
    }
    zipInputStream.closeEntry();
    zipInputStream.close();
    return list;
}

Однако, когда я пытаюсь это сделать, я получаю это исключение (на IOUtils.read)

java.util.zip.ZipException: invalid stored block lengths
   at java.util.zip.InflaterInputStream.read(Unknown Source)
   at java.util.zip.ZipInputStream.read(Unknown Source)

Я делаю это неправильно? Я сделал много ошибок в ошибке, и я не видел ничего, связанного с моей проблемой.

 invalid stored block lengths
 
 
Недопустимая длина хранимых блоков. Это сообщение об ошибке обычно появляется в установке или обновлении базы данных Oracle базы данных или обновления
 


 Есть несколько причин, почему эта ошибка вызвана.
 1. Есть проблема с пакетом загрузки
 2. Проблема в процессе декомпрессии
 3. Есть проблема во время процесса передачи


 решение 
 1. Скачать установочный пакет DB
 2. Реэкстрация
 3. Передача на сервер, по умолчанию открытая двоичная передача
4.restart  server

Перепечатано на: https://blog.51cto.com/evils798/1420912


Интеллектуальная рекомендация

Структура данных Java-реализация стека

Структура данных Java-реализация стека Структура данных Java (1) Введение в стек Интерфейс ADT стека Приложение экземпляра заметки Структура данных Java (1) Структура данных. Введение в стек Структура…

Упаковка и удаление программы Winform

Упаковка и выгрузка программ C # могут быть реализованы в среде IDE Visual Studio. Упакуйте плагин Во-первых, вам необходимо загрузить подключаемый модуль Microsoft Visual Studio Installer Project. Пл…

Вам также может понравиться

Nodejs Development Sides Neademon

После изменения кода необходимо перезапустить приложение Express и модификации, которые вы можете вступить в силу. Если каждая модификация кода повторяется, это повлияет на эффективность разработки. Э…

Устройство для голосования Verilog на 7 человек

7 человек голосуют, когда количество голосов равно 4 или больше (то есть больше половины), выведите 1, чтобы указать, что прошло, в противном случае выведите 0, чтобы указать неудачу. метод первый: Ме…

Основное понимание бинарного дерева

Основная концепция бинарного дерева: Двоичное дерево — это структура дерева, имеющая максимум двух субтотов на узел. Обычно поддерево называют «левым поддеревом» и «правым поддеревом…

Статьи по теме

  • TemplateSyntaxError: Invalid block tag
  • uWSGI invalid request block size (max 4096)
  • XSS (stored)
  • invalid address or address of corrupt block 0xb7feab58 passed to dlfree
  • block
  • Block
  • Block
  • Block
  • block
  • Block

популярные статьи

  • Алгоритм N-арного дерева совершенная успешная версия
  • Раскадровка в iOS использует путь клавиш для установки закругленных углов, границ и цветов заполнителей.
  • IHttpHandler Session
  • Java——Collection
  • Понимание событий Tap Tap Mobile -end (на основе прикосновения)
  • PHP Ручной обзор Глава 4 — Судья, циркуляция
  • CVE-2020-26217: xstream
  • Ошибка ибатиса ошибка счастлива при установке свойства на объекте результата
  • SQL Server 2008 экспортирует данные в виде сценариев [SQL Server]
  • Минимальная инверсия номер — дерево сегмента (одноточечное обновление)

рекомендованная статья

  • [LeetCode Простой вопрос] 72-ход нуля
  • JsonObject JsonArray
  • 4-й промышленные инновационные инновационные инновационные данные о конкуренции и оптимизация регулирования.
  • Пружинный ручной впрыск, динамический впрыск
  • Ты не знаешь JS (в центре) — Часть 1
  • Turn: Пользовательское пространство IO
  • Знание блокировки SQL-сервера и блокировка приложения
  • Python Multi-Process Custom Shared Type Тип данных
  • Загрузите, установите и настройте MySQL-5.7.12-winx64 в среде Windows
  • Как попасть в мое сердце

Связанные теги

  • Фоновое развитие
  • html
  • Учебные примечания
  • структура данных
  • C++
  • ОПРЕДАТЬ АЛгоритм преобразования страниц
  • c++
  • Алгоритм замены страницы
  • операционная система

I’m trying to send some compressed data over the network, I think the data is successfully compressed since I can re-inflate it from the code that deflates the data (written in C), however when the data arrives at my server (nodejs using express) and tries to inflate the data I’m receiving:

{ Error: invalid stored block lengths
    at InflateRaw.zlibOnError (zlib.js:153:15) errno: -3, code: 'Z_DATA_ERROR' }

Any Help will be really appreciated, thanks in advance.

Szz.

P.D: I can provide code snipped if it is useful for anyone.

EDIT:

Thanks for the quick answer and sorry for the delay, I’ve been working in my code, now I’m sending the original data to the server along with the compressed data. When the original data arrives the server I’m deflating it in order to see the buffers generated, surprisingly the buffers of the compressed data sent over the network and the buffer compressed in the server are the same except for the two first bytes particulary:

<Buffer 78 da 15 8c c9 11 00 41 08 02 ff c6 82 55 83 b7 f9 27 b6 ee 13 68 7a a6 b0 4c b8 a7 68 ac 81 61 84 5a 8b e6 82 6b 05 bd aa 44 d9 5e a0 d7 20 6c 2f a6 ... >

<Buffer 15 8c c9 11 00 41 08 02 ff c6 82 55 83 b7 f9 27 b6 ee 13 68 7a a6 b0 4c b8 a7 68 ac 81 61 84 5a 8b e6 82 6b 05 bd aa 44 d9 5e a0 d7 20 6c 2f a6 bf 9b ... >

So, I think my question now is can I assume that this first two bytes will always appear in the compressed data from the C program? Is there any option to avoid this first two bytes? Am I doing well?

Here I leave you the function that compress the data in the C part, the node part is just formidable parsing the post input and a little work with buffers now.

int compress_image (compressed_image raw, size_t size, compressed_image * out) {

    z_stream strm;
    int out_size = 0;

    *out = (compressed_image) malloc(size);

    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;

    int ret = deflateInit(&strm, Z_BEST_COMPRESSION); /* Max compression level, but bad speed performace */

    if (ret != Z_OK)
        return ret;

    strm.avail_in = size;
    strm.next_in = (unsigned char *)raw;

    do {

        strm.avail_out = size;
        strm.next_out = *out;
        ret = deflate(&strm, Z_FINISH);    /* no bad return value */
        assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
        out_size += (size - strm.avail_out);

    } while (strm.avail_out == 0);

    (void)deflateEnd(&strm);

    return out_size;
}

Thanks again!

EDIT 2:
I’m dumping my buffers now and I can see some trailing bytes that differs too,
here you have the buffer coming from C program:

00000000: 78da 158c c911 0041 0802 ffc6 8255 83b7  xÚ..É..A..ÿÆ.U.·
00000010: f927 b6ee 1368 7aa6 b04c b8a7 68ac 8161  ù'¶î.hz¦°L¸§h¬.a
00000020: 845a 8be6 826b 05bd aa44 d95e a0d7 206c  .Z.æ.k.½ªDÙ^.× l
00000030: 2fa6 bf9b 680e f2ce 9c67 975f 0e58 2d91  /¦¿.h.òÎ.g._.X-.
00000040: 75dc f1ed b25c 687a 43dd 42bc 1f98 e7dd  uÜñí²hzCÝB¼..çÝ
00000050: 79a7 99f6 5fd3 bfcc 86f2 01b0 f51a cd    y§.ö_Ó¿Ì.ò.°õ.Í

And the buffer deflated in the server:

00000000: 158c c911 0041 0802 ffc6 8255 83b7 f927  ..É..A..ÿÆ.U.·ù'
00000010: b6ee 1368 7aa6 b04c b8a7 68ac 8161 845a  ¶î.hz¦°L¸§h¬.a.Z
00000020: 8be6 826b 05bd aa44 d95e a0d7 206c 2fa6  .æ.k.½ªDÙ^.× l/¦
00000030: bf9b 680e f2ce 9c67 975f 0e58 2d91 75dc  ¿.h.òÎ.g._.X-.uÜ
00000040: f1ed b25c 687a 43dd 42bc 1f98 e7dd 79a7  ñí²hzCÝB¼..çÝy§
00000050: 99f6 5fd3 bfcc 86f2 01   

However creating a new buffer without the first two bytes I’m able to se my data properly inflated in the server:

my node.js part:

const dump = require('buffer-hexdump');

router.post('/test', function(req, res, next) {

    let form = new formidable.IncomingForm();
    form.uploadDir = "./uploads"

    form.parse(req, function(err, fields, files) {

        let deflated = zlib.deflateRawSync(fs.readFileSync(files.image_raw.path));

        let image_buff = fs.readFileSync(files.image.path);
        let buff = Buffer.alloc(image_buff.length - 2);

        image_buff.copy(buff, 0, 2);

        console.log(buff.equals(deflated)); //false
        console.log(dump(deflated));
        console.log(dump(image_buff));

        zlib.inflateRaw(buff, (err, buffer) => {

            if (err)
                console.error(err);
            else
                console.log(buffer.toString()); //here I can see my data!!

        });

        res.status(200).send("POST received!");

    });
});

I don’t think it is solved however …

Thanks again!

Szz.

Понравилась статья? Поделить с друзьями:
  • Internet explorer ошибка на установить соединение
  • Internet explorer ошибка res common os incompat
  • Internet explorer не запускаются ошибка
  • Internet explorer zonemapping gpo ошибка
  • Internet connection error как исправить ошибку