Unexpected end of zlib input stream как исправить

I’m trying to round-trip a JSON string to a byte array with DeflaterOutputStream, but the code below throwing java.io.EOFException: Unexpected end of ZLIB input stream.

It works when you replace the string with «Hello world», or if you remove a few characters from the string below.

Any ideas?

public static void main(String[] args) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DeflaterOutputStream deflate = new DeflaterOutputStream(bytes, new Deflater(Deflater.BEST_COMPRESSION, true));
    OutputStreamWriter writer = new OutputStreamWriter(deflate);
    writer.write("[1,null,null,"a",null,null,null,null,[1,null,null,null,null,null,null,null,null,null,null,null,null,0.0,0.0,null,null]");
    writer.flush();
    writer.close();

    InflaterInputStream inflaterIn = new InflaterInputStream(new ByteArrayInputStream(bytes.toByteArray()), new Inflater(true));
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inflaterIn));
    System.out.println(bufferedReader.readLine());
}

Java version (OSX):

java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)

In this guide, we will discuss the Java IO EOFException and how to troubleshoot the «Unexpected End of Zlib Input Stream» error. This error is often caused by corrupt or incomplete data being read by the InflaterInputStream class. We will provide step-by-step solutions for resolving this issue and preventing it from happening in the future.

Table of Contents

  1. Understanding the Java IO EOFException
  2. Identifying the Cause of the Error
  3. Step-by-Step Solutions
  4. FAQ
  5. Related Links

Understanding the Java IO EOFException

The Java IO EOFException (End Of File Exception) is a type of IOException that occurs when the end of an input stream is reached unexpectedly during input operations. In the context of the Zlib library, this error is thrown when the InflaterInputStream class encounters an unexpected end of the compressed input stream while attempting to decompress it.

This error can occur due to various reasons, such as:

  • Corrupt or incomplete compressed data
  • Incorrect usage of the InflaterInputStream class
  • Network issues causing incomplete data transfer

Before diving into the solutions, it’s essential to identify the root cause of the issue.

Identifying the Cause of the Error

To track down the error’s cause, you can perform the following checks:

  1. Verify the integrity of the compressed data: Make sure the data being decompressed is not corrupt or incomplete. You can test this by decompressing the data using a different decompression tool, like 7-Zip.
  2. Check the usage of the InflaterInputStream class: Ensure you are using the correct constructor and not accidentally setting the nowrap parameter to true. Setting the nowrap parameter to true disables the Zlib header and checksum processing, which can cause the error.
  3. Monitor network transfers: If the data is being transmitted over a network, verify that the complete data is being received before attempting to decompress it.

Once you have determined the cause, you can proceed with the appropriate solution.

Step-by-Step Solutions

Solution 1: Fixing Corrupt or Incomplete Data

If the cause of the error is corrupt or incomplete data, you can try the following steps to resolve the issue:

  1. Re-download or regenerate the compressed data.
  2. Verify the integrity of the data using a decompression tool like 7-Zip.
  3. Retry decompression using the InflaterInputStream class.

Solution 2: Correct Usage of the InflaterInputStream Class

Ensure you are using the correct constructor for the InflaterInputStream class. The default constructor uses Zlib header and checksum processing, which should be used in most cases. Here’s an example of the correct usage:

InputStream inputStream = new FileInputStream("compressed-data.zlib");
InflaterInputStream inflaterInputStream = new InflaterInputStream(inputStream);

Avoid using the nowrap parameter set to true unless you are certain that the compressed data does not include Zlib headers and checksums:

InputStream inputStream = new FileInputStream("compressed-data.zlib");
Inflater inflater = new Inflater(true); // Setting nowrap to true
InflaterInputStream inflaterInputStream = new InflaterInputStream(inputStream, inflater);

Solution 3: Ensuring Complete Data Transfer

If the error is caused by incomplete data transfer over a network, you can try the following steps:

  1. Implement error-handling and retry mechanisms for network transfers.
  2. Verify the integrity of the received data before attempting to decompress it.
  3. Consider using a more reliable transfer protocol, like TCP, to ensure complete data transmission.

FAQ

1. What is the Java IO EOFException?

The Java IO EOFException is a type of IOException that occurs when the end of an input stream is reached unexpectedly during input operations.

2. What causes the «Unexpected End of Zlib Input Stream» error?

This error is often caused by corrupt or incomplete data being read by the InflaterInputStream class or incorrect usage of the InflaterInputStream class.

3. How can I verify the integrity of compressed data?

You can verify the integrity of compressed data by decompressing it using a different decompression tool, like 7-Zip, and checking for any errors.

4. What is the nowrap parameter in the InflaterInputStream class?

The nowrap parameter in the InflaterInputStream class is a flag that, when set to true, disables Zlib header and checksum processing.

5. Can network issues cause the «Unexpected End of Zlib Input Stream» error?

Yes, network issues can cause incomplete data transfer, which can lead to this error when attempting to decompress the data.

  • Java IO EOFException (Oracle Documentation)
  • InflaterInputStream (Oracle Documentation)
  • Zlib Compression Library
  • 7-Zip

Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.

Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

2017-10-03_153645.png

Полная печать исключения состоит из 3-х частей:

  1. Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
  2. Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
  3. Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).

Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.

В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).

При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.

org.lwjgl.LWJGLException: Pixel format not accelerated
Недоступно аппаратное ускорение графики. Описание ошибки (англ.)

Решение: Установите последнюю версию драйвера видеокарты.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.

Что можно сделать:

  • Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
  • Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.

java.net.SocketTimeOutException: Read timed out
Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.

Что можно сделать:

  • Отключите антивирус и попробуйте выполнить запрос снова.
  • Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
  • Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.

java.net.ConnectException: Connection timed out: connect
Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.

Что можно сделать:

  • Проверьте наличие подключения к интернету.
  • Временно отключите антивирус и Firewall.

java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.

java.lang.ClassCastException: XXX cannot be cast to YYY
Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.io.IOException: Server returned HTTP response code: 000 for URL
Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».

Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.

java.lang.UnsatisfiedLinkError: Can’t load library:
Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).

Что можно сделать:

  • Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
    Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.

java.lang.RuntimeException: Unknown character in
Синтаксическая ошибка в конфигурационном файле мода.

Что можно сделать:

  • Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
  • Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
  • Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.

java.lang.NullPointerException (NPE)
Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.net.UnknownHostException
Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).

Что можно сделать:

  • Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
  • Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.

java.io.EOFException: Unexpected end of ZLIB input stream
Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.

java.net.SocketException: Address family not supported by protocol family: connect
Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.

image.png

java.lang.OutOfMemoryError
А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:

  • Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
  • Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.

I get a Unexpected end of ZLIB input stream error when I try to read a model, I committed before. I have tried the SingleCheckinAndDownload.java example and the error occurs to. After a commit the 3D-view in bimviews does also not work. There is only the loading project bar but without progress. Is there something wrong with my code or is there a problem with the server?

Error :

[AWT-EventQueue-0] INFO org.bimserver.emf.SharedJsonDeserializer — # Objects: 1772
java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:67)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744)
at org.bimserver.client.ClientIfcModel.loadGeometry(ClientIfcModel.java:347)
at org.bimserver.client.ClientIfcModel.loadDeep(ClientIfcModel.java:303)
at org.bimserver.client.ClientIfcModel.(ClientIfcModel.java:115)
at org.bimserver.client.BimServerClient.getModel(BimServerClient.java:202)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:316)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:491)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.jComboBox1ActionPerformed(ProjectGUI.java:410)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.access$000(ProjectGUI.java:30)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI$1.actionPerformed(ProjectGUI.java:147)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:861)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:510)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code for read model:

public static BimServerClient getclient(String url, String user, String passwd) {
    try {
        JsonBimServerClientFactory factory = new JsonBimServerClientFactory(url);
        try (BimServerClient client = factory.create(new UsernamePasswordAuthenticationInfo(user, passwd))) {
            return client;
        } catch (org.bimserver.shared.exceptions.UserException ex) {
            IO.outerror("Benutzername oder Passwort wurde nicht akzeptiert!", "Fehler bei Verbindung");
            return null;
        } catch (org.bimserver.shared.reflector.ReflectorException ex) {
            IO.outerror("Server konnte nicht gefunden werden!", "Fehler bei Verbindung");
            return null;
        } catch (Exception ex) {
            IO.outerror(ex.getMessage(), "Fehler bei Verbindung");
            return null;
        }
    } catch (BimServerClientException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

 public void setproject(org.bimserver.interfaces.objects.SProject project) {
    this.project = project;
    setisifc();
    if (project.getLastRevisionId() < 0) {
        return;
    }
    javax.swing.JDialog d = createwait();
    try {
        model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        if (isifc2()) {
            ifc2ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc2x3tc1.IfcProduct.class);
        }
        if (isifc4()) {
            ifc4ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc4.IfcProduct.class);
        }
    } catch (UserException | ServerException ex) {
        Logger.getLogger(globalsets.class.getName()).log(Level.SEVERE, null, ex);
    }
    d.dispose();
}

Code for commit:

private void jButtoncommitActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try {
        String comtext = JOptionPane.showInputDialog("Bitte Text für commit eingeben:  ");
        if (comtext == null) {
            return;
        }
        IO.o("TransactionID: " + globalset.getmodel().getTransactionId());
        globalset.getmodel().fixOidCounter();
        globalset.getmodel().fixOids();
        //globalset.getmodel().fixInverseMismatches();

        //globalset.getmodel().checkDoubleOidsPlusReferences();
        //globalset.getclient().commit(globalset.getmodel(), comtext);
       // globalset.getmodel().checkin(globalset.getproject().getRid(), comtext);
        javax.swing.JDialog d = globalset.createwait("Daten werden auf den Bimserver übertragen!");
        IO.o(globalset.getmodel().commit(comtext));
        d.dispose();
        IO.o("commited");
        IO.o(globalset.getmodel().getTransactionId());
        d = globalset.createwait("Model des Bimservers wird neu geladen!");
        //model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        globalset.setmodel(globalset.getclient().getModel(globalset.getproject(), 
        globalset.getproject().getLastRevisionId(), true, true));
        d.dispose();
        IO.o(globalset.getmodel().getTransactionId());
    } catch (ServerException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UserException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PublicInterfaceNotFoundException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BimServerClientException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}                                             

Problem

The Modeler .str file has become corrupt. No recovery exists for the explicit file. If no further action is done within Modeler, the backup .str- file may be intact.

Symptom

«Unexpected end of ZLIB input stream»

Cause

The error message means that the stream file is invalid. The compression procedure involved in creating a stream file is performed by the Java Virtual Machine that is responsible for handling the User Interface. If Modeler Client is closed before the stream has finished saving, then the resulting stream file will be incomplete. To date this problem has been reported only on a few occasions and the lack of available information into the environment leading up to this problem means the problem has not been replicated. If you see Modeler client using a lot of RAM (that the two numbers in the bottom right-hand-corner of the Modeler workpane are very close to each other), then it is possible that saving a large stream within that session will take a significant amount of time as the JVM is using as much memory as it is currently allowed to. In this situation please allow the stream save process to complete — the presence of the hourglass cursor within Modeler client for an extended time in this situation does not indicate an application hang and therefore does not indicate in itself the need for a forceful termination of the process.

We are investigating if we can make it clearer to the user that the stream save is still in progress.

Note it is possible for external factors to corrupt Modeler streams just as they can corrupt any files. If you have Modeler streams that suddenly appear corrupt, but Modeler hasn’t been used to load or save them since previously successful use, then it is likely that something external has corrupted the files on your filesystem. If this is the case please restore the files from backup as you would in the event of corruption of any other file types.

Resolving The Problem

If you experience this issue the stream cannot be recovered, although the backup stream of the same name (but with suffix ‘.str-‘) should be intact. Please delete the corrupted original and use the previous backup stream.

If you have a specific stream that causes this when you attempt to reload it, and the save within Modeler appears to complete (ie. the UI returns for use from the busy hourglass cursor), then please, if possible, follow these steps:

1. Copy the backup stream in Windows explorer (the stream with the same name but with the «.str-» extension to , eg. «mybackup.str» — retain this stream as a master backup).
2. open the backup stream (with the same name as the original stream but a «.str-» extension)
3. document the exact steps that were taken to modify the backup stream so that it is in the exact state it was in immediately before the final save that created the stream file that you can no longer load without this error.
4. Confirm that it is repeatable (ie. confirm that if you again save the stream that you get the same error when you try to reload it into Modeler)
5. If it is, please provide the backup stream, «my backup.str» along with the documentation of the steps you made in step 3. so we can attempt to replicate the issue.

Related Information

[{«Product»:{«code»:»SS3RA7″,»label»:»IBM SPSS Modeler»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Modeler»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»Not Applicable»,»Edition»:»All Editions;Workstation»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как составить табель учета рабочего времени преподавателей
  • Как найти сотрудников в молодую компанию
  • Как найти наибольшее значение дроби с корнями
  • Как найти поставщика с завода
  • Песня такого как я нигде не найти

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии