Ошибка в лаунчере java io eofexception

      Не удалось распаковать Java Runtime.

В большинстве случаев в этой проблеме виноват антивирус. Попробуйте выключить его и попробовать снова.

Информация для разработчиков:

java.io.EOFException: Unexpected end of ZLIB input stream

at java.util.zip.InflaterInputStream.fill(Unknown Source)

at java.util.zip.InflaterInputStream.read(Unknown Source)

at java.util.zip.ZipInputStream.read(Unknown Source)

at java.io.FilterInputStream.read(Unknown Source)

at ru.vimeworld.updater.Utils.unzip(Utils.java:141)

at ru.vimeworld.updater.Main.main(Main.java:193)

Вот что пишет при заходе

The java.io.EOFException is a checked exception in Java that occurs when an end of file or end of stream is reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream.

Since EOFException is a checked exception, it must be explicitly handled in methods that can throw this exception — either by using a try-catch block or by throwing it using the throws clause.

What Causes EOFException

While reading the contents of a file or stream using DataInputStream objects, if the end of the file or stream is reached unexpectedly, an EOFException is thrown. Methods of the DataInputStream class that are used to read data such as readBoolean(), readByte() and readChar() can throw this exception.

Many other input operations return a special value on end of file or stream rather than throwing an exception.

EOFException Example

Here’s an example of a EOFException thrown when trying to read all characters from an input file:

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class EOFExceptionExample {
    public static void main(String[] args) {
        DataInputStream inputStream = null;

        try {
            inputStream = new DataInputStream(new FileInputStream("myfile.txt"));

            while (true) {
                inputStream.readChar();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

In the above example, the contents of a file with the name myfile.txt are read in an infinite loop using the DataInputStream.readChar() method. When the readChar() method is called at the end of the file, an EOFException is thrown:

java.io.EOFException
    at java.base/java.io.DataInputStream.readChar(DataInputStream.java:369)
    at EOFExceptionExample.main(EOFExceptionExample.java:13)

How to Fix EOFException

Since EOFException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.

The above example can be updated to handle the EOFException in a try-catch block:

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;

public class EOFExceptionExample {
    public static void main(String[] args) {
        DataInputStream inputStream = null;

        try {
            inputStream = new DataInputStream(new FileInputStream("myfile.txt"));

            while (true) {
                try {
                    inputStream.readChar();
                } catch (EOFException eofe) {
                    System.out.println("End of file reached");
                    break;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

Here, the inputStream.readChar() method call is placed in a try block and the EOFException is caught inside the catch block. When an EOFException occurs at the end of the file, it is handled and a break statement is used to break out of the loop.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

I’m a beginner java programmer following the java tutorials.

I am using a simple Java Program from the Java tutorials’s Data Streams Page, and at runtime, it keeps on showing EOFException. I was wondering if this was normal, as the reader has to come to the end of the file eventually.

import java.io.*;

public class DataStreams {
    static final String dataFile = "F://Java//DataStreams//invoicedata.txt";

    static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    static final int[] units = { 12, 8, 13, 29, 50 };
    static final String[] descs = {
        "Java T-shirt",
        "Java Mug",
        "Duke Juggling Dolls",
        "Java Pin",
        "Java Key Chain"
    };
    public static void main(String args[]) {
        try {
            DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

            for (int i = 0; i < prices.length; i ++) {
                out.writeDouble(prices[i]);
                out.writeInt(units[i]);
                out.writeUTF(descs[i]);
            }

            out.close(); 

        } catch(IOException e){
            e.printStackTrace(); // used to be System.err.println();
        }

        double price;
        int unit;
        String desc;
        double total = 0.0;

        try {
            DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

            while (true) {
                price = in.readDouble();
                unit = in.readInt();
                desc = in.readUTF();
                System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                unit, desc, price);
                total += unit * price;
            }
        } catch(IOException e) {
            e.printStackTrace(); 
        }

        System.out.format("Your total is %f.%n" , total);
    }
}

It compiles fine, but the output is:

You ordered 12 units of Java T-shirt at $19.99
You ordered 8 units of Java Mug at $9.99
You ordered 13 units of Duke Juggling Dolls at $15.99
You ordered 29 units of Java Pin at $3.99
You ordered 50 units of Java Key Chain at $4.99
java.io.EOFException
        at java.io.DataInputStream.readFully(Unknown Source)
        at java.io.DataInputStream.readLong(Unknown Source)
        at java.io.DataInputStream.readDouble(Unknown Source)
        at DataStreams.main(DataStreams.java:39)
Your total is 892.880000.

From the Java tutorials’s Data Streams Page, it says:

Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.

So, does this mean that catching EOFException is normal, so just catching it and not handling it is fine, meaning that the end of file is reached?

If it means I should handle it, please advise me on how to do it.

EDIT

From the suggestions, I’ve fixed it by using in.available() > 0 for the while loop condition.

Or, I could do nothing to handle the exception, because it’s fine.

Contents of page >

  • What is hierarchy of java.lang. EOFException?

  • EOFException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

  • What is EOFException in java?

  • Example/Programs/Scenarios where EOFException may be thrown in java>

  • How to avoid EOFException in java?

    • Solution 1) You may persist some count in file during serialization process to find out exactly how many object were actually serialized and simply use for loop in place of while loop in deserialization process.

    • Solution 2) I’ll recommend you this solution, probably the best solution

      • Create a class EofIndicatorClass which implements Serializable interface.

What is hierarchy of java.lang. EOFException?

-java.lang.Object

-java.lang.Throwable

   -java.lang.EOFException

EOFException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

java.lang.EOFException is a Checked (compile time) Exception in java.

What is EOFException in java?

EOFException is the End of file Exception. Many input streams through EOFException to indicate end of file (Few Java Api doesn’t provide any elegant solution to signify end the file). EOFException could be thrown >

  1. During DESERIALIZATION of object (when we are reading object using input stream).

  2. During use of RandomAccessFile, by using seek method we can move to random position, if seek is set beyond the length the file and we try to read from there than java.io.EOFException is thrown.

Now let’s discuss above two points with program and examples.

Example/Programs/Scenarios where EOFException may be thrown in java>

SERIALIZATION>

Create object of ObjectOutput and give its reference variable name oout and call writeObject() method and pass our employee object as parameter [oout.writeObject(object1) ]

OutputStream fout = new FileOutputStream(«ser.txt»);

ObjectOutput oout = new ObjectOutputStream(fout);

System.out.println(«Serialization process has started, serializing employee objects…«);

oout.writeObject(object1);

Program to Serialize Object>

package SerDeser1;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.io.Serializable;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal  Copyright- contents must not be reproduced in any form*/

class Employee implements Serializable {

   private static final long serialVersionUID = 1L;

   private Integer id;

   private String name;

   public Employee(Integer id, String name) {

          this.id = id;

          this.name = name;

   }

   @Override

   public String toString() {

          return «Employee [id=» + id + «, name=» + name + «]»;

   }

}

public class SerializeEmployee {

   public static void main(String[] args) {

          Employee object1 = new Employee(1, «amy»);

          Employee object2 = new Employee(2, «ankit»);

          try {

                 OutputStream fout = new FileOutputStream(«ser.txt»);

                 ObjectOutput oout = new ObjectOutputStream(fout);

                 System.out.println(«Serialization process has started, serializing employee objects…»);

                 oout.writeObject(object1);

                 oout.writeObject(object2);

                   oout.close();

                 System.out.println(«Object Serialization completed.»);

          } catch (IOException ioe) {

                 ioe.printStackTrace();

          }

   }

}

/*OUTPUT

Serialization process has started, serializing employee objects…

Object Serialization completed.

*/

DESERIALIZATION>

Create object of ObjectInput and give it’s reference variable name oin and call readObject() method [oin.readObject() ]

InputStream fin=new FileInputStream(«ser.txt»);

ObjectInput oin=new ObjectInputStream(fin);

System.out.println(«DeSerialization process has started, displaying employee objects…»);

Employee emp;

emp=(Employee)oin.readObject();

Program to DeSerialize object>

import java.io.EOFException;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInput;

import java.io.ObjectInputStream;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal  Copyright- contents must not be reproduced in any form*/

public class DeSerializeEmployee {

   public static void main(String[] args) {

          InputStream fin;

          try {

                 fin = new FileInputStream(«ser.txt»);

                 ObjectInput oin = new ObjectInputStream(fin);

                 System.out.println(«DeSerialization process has started, «

                              + «displaying employee objects…»);

                 Employee emp;

                 while ((emp = (Employee) oin.readObject()) != null) {

                       System.out.println(emp);

                 }

                 oin.close();

          } catch (EOFException e) {

                 System.out.println(«File ended»);

          }  catch (FileNotFoundException e) {

                 e.printStackTrace();

          } catch (IOException e) {

                 e.printStackTrace();

          } catch (ClassNotFoundException e) {

                 e.printStackTrace();

          }

          System.out.println(«Object DeSerialization completed.»);

   }

}

/*OUTPUT

DeSerialization process has started, displaying employee objects…

Employee [id=1, name=amy]

Employee [id=2, name=ankit]

File ended

Object DeSerialization completed.

*/

In the above program when file is read till end using readObject() in while loop then EOFException is thrown. Java Api doesn’t provide any elegant solution to signify end the file.

By using seek method we can move to random position, if seek is set beyond the length the file and we try to read from there than java.io.EOFException is thrown.

Program to read/write from file using RandomAccessFile >

Note : Before executing below program, remove everything from c:/myFile.txt for better understanding of program

Or preferably you may delete this file because if file doesn’t exist than RandomAccessFile will create new file.

import java.io.IOException;

import java.io.RandomAccessFile;

public class RandomAccessFileTest {

public static void main(String[] args) {

     try {

          String fileName = «c:/myFile.txt»;

          String data = «abcdef»;

          RandomAccessFile randomAccessFile;

          // —- Writing in file using RandomAccessFile —-

          // ‘rw‘ means opening file in Read-Write mode

          randomAccessFile = new RandomAccessFile(fileName, «rw»);

          randomAccessFile.seek(5);

          randomAccessFile.writeUTF(data);

          System.out.println(«Data written in «+» = «+data);

          randomAccessFile.close();

          // —- Reading from file using RandomAccessFile —-

          // ‘r’ means opening file in Read mode

          randomAccessFile = new RandomAccessFile(fileName, «r»);

          randomAccessFile.seek(5);

          data = randomAccessFile.readUTF();

          System.out.println(«Data read from file = «+data);

          randomAccessFile.close();

     } catch (IOException e) {

          e.printStackTrace();

     }

}

}

/*

Data written in file = abcdef

Data read from file = abcdef

*/

After executing above program c:/myFile.txt will look like this >

How to avoid EOFException in java?

During deserialization process when file is read till end using readObject() in while loop then EOFException is thrown as we saw in DeSerialization program. Java Api doesn’t provide any elegant solution to signify end the file.

Generally what we could except at EOF(end of file) is null but that doesn’t happen.

So, we’ll try to address the problem because catching EOFException and interpreting it as EOF is not the elegant solution because sometimes you may fail to detect a normal EOF of a file that has been truncated.

So, let’s discuss best possible solution to address the EOFException >

  • Solution 1) You may persist some count in file during serialization process to find out exactly how many object were actually serialized and simply use for loop in place of while loop in deserialization process.

Or,

  • Solution 2) I’ll recommend you this solution, probably the best solution

    • Create a class EofIndicatorClass which implements Serializable interface.

    • During serialization >

      • Write instance of EofIndicatorClass at EOF during serialization to indicate EOF during deSerialization process.

    • During serialization >

      • If oin.readObject() returns instanceof EofIndicatorClass that means it’s EOF, exit while loop and EOFException will not be thrown.

Now, let’s discuss solution 2 in detail.

Program to Serialize Object and persisting EofIndicatorClass at EOF >

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.io.Serializable;

/*

* Class whose instance will be written at EOF during serialization

* to indicate EOF during deSerialization process.

*/

class EofIndicatorClass implements Serializable{}

/*Author : AnkitMittal  Copyright- contents must not be reproduced in any form*/

class Employee implements Serializable {

   private static final long serialVersionUID = 1L;

   private String name;

   public Employee(String name) {

          this.name = name;

   }

   @Override

   public String toString() {

          return «Employee [name=» + name + «]»;

   }

}

/*

* Serialization class

*/

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class SerializeEmployee {

   public static void main(String[] args) {

          Employee object1 = new Employee( «amy»);

          Employee object2 = new Employee( «ankit»);

          try {

                 OutputStream fout = new FileOutputStream(«ser.txt»);

                 ObjectOutput oout = new ObjectOutputStream(fout);

                 System.out.println(«Serialization process has started, «

                              + «serializing employee objects…»);

                 oout.writeObject(object1);

                 oout.writeObject(object2);

                 //write instance of EofIndicatorClass at EOF

                 oout.writeObject(new EofIndicatorClass());

                 oout.close();

                 System.out.println(«Object Serialization completed.»);

          } catch (IOException ioe) {

                 ioe.printStackTrace();

          }

   }

}

/*OUTPUT

Serialization process has started, serializing employee objects…

Object Serialization completed.

*/

Program to DeSerialize object and detecting EOF without throwing EOFException >

Avoid ObjectInputStream.readObject() from throwing EOFException at End Of File in java

import java.io.EOFException;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInput;

import java.io.ObjectInputStream;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class DeSerializeEmployee {

   public static void main(String[] args) {

          InputStream fin;

          try {

                 fin = new FileInputStream(«ser.txt»);

                 ObjectInput oin = new ObjectInputStream(fin);

                 System.out.println(«DeSerialization process has started, «

                              + «displaying employee objects…»);

                  /*

                 *If oin.readObject() returns instanceof EofIndicatorClass that means

                 *it’s EOF, exit while loop and EOFException will not be thrown.

                 */

                Object obj;

                while(!((obj =  oin.readObject()) instanceof EofIndicatorClass)){

                     System.out.println(obj);

                }

                  oin.close();

          } catch (EOFException e) {

                 System.out.println(«File ended»);

          }  catch (FileNotFoundException e) {

                 e.printStackTrace();

          } catch (IOException e) {

                 e.printStackTrace();

          } catch (ClassNotFoundException e) {

                 e.printStackTrace();

          }

          System.out.println(«Object DeSerialization completed.»);

   }

}

/*OUTPUT

DeSerialization process has started, displaying employee objects…

Employee [name=amy]

Employee [name=ankit]

Object DeSerialization completed.

*/

If you note output of program EOFException wasn’t thrown, you may compare output of the program with DeSerialization done in this post where EOFException was thrown.

Summary >

So in this Exception handling java tutorial we learned what is hierarchy of java.lang. EOFException? java.lang.EOFException is a Checked (compile time) Exception in java. What is EOFException in java? Example/Programs/Scenarios where EOFException may be thrown in java. How to avoid EOFException in java?

Having any doubt? or you you liked the tutorial! Please comment in below section.

RELATED LINKS>

Most common and frequently occurring checked (compile time) and Errors in java >

  • IOException and how to solve it in java

  • EOFException in java

  • SQLException in java

  • What is java.lang.InterruptedException in java

  • when java.lang.ClassNotFoundException occurs in java

Most common and frequently occurring unchecked (runtime) in java.

  • What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and fix it

  • NumberFormatException in java

  • IndexOutOfBoundsException in java

  • When java.lang.ArrayIndexOutOfBoundsException occurs in java

  • When java.lang.StringIndexOutOfBoundsException occurs in java

  • java.lang.ArithmeticException in java — Divide number by zero

  • When dividing by zero does not throw ArithmeticException in java

  • When java.lang.IllegalStateException occurs in java

  • when java.lang.IllegalMonitorStateException is thrown in java

  • Solve java.lang.UnsupportedOperationException in java

Most common and frequently occurring Errors in java >

  • OutOfMemoryError in java

  • When java.lang.StackOverflowError occurs in java

  • Solve java.lang.ExceptionInInitializerError in java

  • How to solve java.lang.NoClassDefFoundError in java

Few More >

  • What is difference between ClassNotFoundException and NoClassDefFoundError in java

While reading the contents of a file in certain scenarios the end of the file will be reached in such scenarios a EOFException is thrown.

Especially, this exception is thrown while reading data using the Input stream objects. In other scenarios a specific value will be thrown when the end of file reached.

Example

Let us consider the DataInputStream class, it provides various methods such as readboolean(), readByte(), readChar() etc.. to read primitive values. While reading data from a file using these methods when the end of file is reached an EOFException is thrown.

import java.io.DataInputStream;
import java.io.FileInputStream;
public class EOFExample {
   public static void main(String[] args) throws Exception {
      //Reading from the above created file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:data.txt"));
      while(true) {
         char ch;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}

Runtime Exception

Hello how are youException in thread "main" java.io.EOFException
   at java.io.DataInputStream.readChar(Unknown Source)
   at SEPTEMBER.remaining.EOFExample.main(EOFExample.java:11)

Handling EOFException

You cannot read contents of a file without reaching end of the file using the DataInputStream class. If you want, you can use other sub classes of the InputStream interface.

Example

In the following example we have rewritten the above program using FileInputStream class instead of DataInputStream to read data from a file.

 Live Demo

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String[] args) throws Exception {
      //Reading data from user
      byte[] buf = " Hello how are you".getBytes();
      //Writing it to a file using the DataOutputStream
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:data.txt"));
      for (byte b:buf) {
         dos.writeChar(b);
      }
      dos.flush();
      System.out.println("Data written successfully");
   }
}

Output

Data written successfully

Following is another way to handle EOFException in Java −

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class HandlingEOF {
   public static void main(String[] args) throws Exception {
      DataInputStream dis = new DataInputStream(new FileInputStream("D:data.txt"));
      while(true) {
         char ch;
         try {
            ch = dis.readChar();
            System.out.print(ch);
         } catch (EOFException e) {
            System.out.println("");
            System.out.println("End of file reached");
            break;
         } catch (IOException e) {
         }
      }
   }
}

Output

Hello how are you
End of file reached

In this tutorial we will discuss about the EOFException in Java. This exception indicates the the end of file (EOF), or the end of stream has been reached unexpectedly. Also, this exception is mainly used by DataInputStreams, in order to signal the end of stream. However, notice that other input operations may return a special value upon the end of a stream, instead of throwing an EOFException.

The EOFException class extends the IOException class, which is the general class of exceptions produced by failed, or interrupted I/O operations. Moreover, it implements the Serializable interface. Also, it is defined as a checked exception and thus, it must be declared in a method, or a constructor’s throws clause.

Finally, the EOFException exists since the 1.0 version of Java.

The Structure of EOFException

Constructors

  • EOFException()
  • Creates an instance of the EOFException class, setting null as its message.

  • EOFException(String s)
  • Creates an instance of the EOFException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The EOFException in Java

DataInputStreams provide methods that can read primitive Java data types from an underlying input stream in a machine-independent way. An application writes data, by using the methods provided by the OutputStream class, or the DataOutputStream class.

Specifically, primitive types can be read by an application, using one of the following methods:

  • readBoolean() – Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
  • readByte() – Reads and returns one input byte.
  • readChar() – Reads two input bytes and returns a char value.
  • readDouble() – Reads eight input bytes and returns a double value.
  • readFloat() – Reads four input bytes and returns a float value.
  • readInt() – Reads four input bytes and returns an int value.
  • readLong() – Reads eight input bytes and returns a long value.
  • readShort() – Reads two input bytes and returns a short value.
  • readUnsignedByte() – Reads one input byte and returns it as a zero-extended int value. The integer value resides in the range [0, 255].
  • readUnsignedShort() – Reads two input bytes and returns them as an int value. The integer value resides in the range [0, 65535].

For a list of all available methods, take a closer look on the DataInputStream class.

The following example reads all characters from an input file:

EOFExceptionExample.java:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class EOFExceptionExample {
	
	//The name of the input file.
	private final static String FILENAME = "input.txt";
	
	private static void writeToFile() throws IOException {
		DataOutputStream out = new DataOutputStream(new FileOutputStream(FILENAME));
		
		//Write a string to the stream.
		String str = "Hello from Java Code Geeks!";
		for(int i = 0; i < str.length(); ++i)
			out.writeChar(str.charAt(i));
		
		//Close the data stream.
		out.close();
		
		return;
	}
	
	public static void main(String[] args) {
		DataInputStream input = null;
		try {
			//Write some integers to the file.
			writeToFile();
			
			// Read all characters, until an EOFException is thrown.
			input = new DataInputStream(new FileInputStream(FILENAME));
			while(true) {
				char num;
				try {
					num = input.readChar();
					System.out.println("Reading from file: " + num);
				}
				catch (EOFException ex1) {
					break; //EOF reached.
				}
				catch (IOException ex2) {
					System.err.println("An IOException was caught: " + ex2.getMessage());
					ex2.printStackTrace();
				}
			}
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			try {
				// Close the input stream.
				input.close();
			}
			catch(IOException ex) {
				System.err.println("An IOException was caught: " + ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

In this example we first, write a string to a file and then, use the readChar() method to read all written characters one-by-one.

A sample execution is shown below:

Reading from file: H
Reading from file: e
Reading from file: l
Reading from file: l
Reading from file: o
Reading from file:  
Reading from file: f
Reading from file: r
Reading from file: o
Reading from file: m
Reading from file:  
Reading from file: J
Reading from file: a
Reading from file: v
Reading from file: a
Reading from file:  
Reading from file: C
Reading from file: o
Reading from file: d
Reading from file: e
Reading from file:  
Reading from file: G
Reading from file: e
Reading from file: e
Reading from file: k
Reading from file: s
Reading from file: !

Once the EOFException is thrown, we only have to break from the reading loop and then, close the stream.

Download the Eclipse Project

This was a tutorial about the EOFException in Java.

Exception in thread «main» java.io.eofexception

In this post i am going to discuss about the End of File(EOF) exception.EOFexception extends IOException and is thrown while performing I/O operations.

This exception is usually thrown when the end of file (EOF) is reached unexpectedly while reading the input file.Note that,this exception will also be thrown if the input file contains no data in it.

I have explained this EOF exception with the following program.The following program tries to read the file «exam.txt» and prints its contents.When the reader has reached the end of the file i have thrown the EOF exception to indicate that the file has reached its end.

Program:

import java.io.*;

public class Example1
{

public static void main(String[] args)throws IOException
{
BufferedReader br=null;
try
{
File f=new File(«E:/exam.txt»);
FileReader reader = new FileReader(f);
br = new BufferedReader(reader);
String strcontent =null;
while(true)
{
if((strcontent=br.readLine()) != null)
{
System.out.println(strcontent);
}
else
{
throw new EOFException();
}
}

}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(EOFException e1)
{
br.close();
System.out.println(«The file has reached its end»);
}
}
}

Thus in the above code the statement «throw new EOFException()» is used to explicily indicate the end of the file and perform the necessary actions rather than letting jvm to deal with it.

In the above program if you do not include the statement throw new EOFException then it will not get terminated.

Sometimes this exception may occur due to an error in the input file.For eg. if the header of the file indicates that the content length of the file is 1000 characters but if you encounter the EOF character after reading some 200 characters.In this situation EOFException can be used to deal with it.

NOTE:


1.When we use Scanner object to read from a file then java.util.NoSuchElementException is thrown if the end of file (EOF) is reached.
2.If we use BufferedReader object to read from a file then no exception will be thrown upon reaching the end of the file.
3. If we use DataInputStream object to read from a file then this EOFException will be thrown if  the reader has reached the end of the file.

I have also explained, how using DataInputStream Object  to read a file throws the EOFException  in the following program.

Program:

import java.io.*;

import java.util.*;

public class Fileclassread

{

public static void main(String args[])

{

String line;

try

{

DataInputStream in=new DataInputStream(new FileInputStream(«Child1.class»));

int bytesavailable=in.available();

System.out.println(«Total no of bytes in the file «+bytesavailable);

for(int i=0;i

{

if(in.readInt()==0xCAFEBABE)

{

System.out.println(«The minor version number:»+in.readShort());

System.out.println(«The major version number:»+in.readShort());

}

}

}

catch(EOFException e)

{

System.out.println(«the file has reached its end…»);

}

catch(IOException e)

{

e.printStackTrace();

}

}

}

output:

Total number of bytes in the file 227

The minor version number:0

The major version number:50

java.io.EOFException

        at java.io.DataInputStream.readInt(Unknown Source)

        at Fileclassread.main(Fileclassread.java:18)

If you see the output of the program,the first line shows how many bytes available in the class file.

Since readInt() will read 4 bytes of data at a time,the for loop should be limited to the value of 55,

because the two readShort() contributes the other 4 bytes.So a total of 224 bytes will be read.

The remaining 3 bytes cannot be read by using readInt() as it requires 4 bytes.Thus java.io.EOFException is thrown.

Я хочу прочитать файл и если там email существует — ничего не делать, а если не существует — записать email в файл.

private void readEmail(String file, Email emails) {
    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Email email;
        while ((email = (Email) objectInputStream.readObject()) == null || (email = (Email) objectInputStream.readObject()) != null) {
            if (!emails.getEmail().equals(email)) {
                writeInFile(file, emails);
            } else {
                System.out.println("User already exist!");
            }
        }
        objectInputStream.close();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Sergey-N13's user avatar

How to avoid EOFException in java?

During deserialization process when file is read till end using readObject() in while loop then EOFException is thrown as we saw in DeSerialization program. Java Api doesn’t provide any elegant solution to signify end the file.

Generally what we could except at EOF(end of file) is null but that doesn’t happen.

So, we’ll try to address the problem because catching EOFException and interpreting it as EOF is not the elegant solution because sometimes you may fail to detect a normal EOF of a file that has been truncated.

So, let’s discuss best possible solution to address the EOFException >

  • Solution 1) You may persist some count in file during serialization process to find out exactly how many object were actually serialized and simply use for loop in place of while loop in deserialization process.

Or,

  • Solution 2) I’ll recommend you this solution, probably the best solution

    • Create a class EofIndicatorClass which implements Serializable interface.

    • During serialization >

      • Write instance of EofIndicatorClass at EOF during serialization to indicate EOF during deSerialization process.

    • During serialization >

      • If oin.readObject() returns instanceof EofIndicatorClass that means it’s EOF, exit while loop and EOFException will not be thrown.

Now, let’s discuss solution 2 in detail.

Program to Serialize Object and persisting EofIndicatorClass at EOF >

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutput;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

import java.io.Serializable;

/*

* Class whose instance will be written at EOF during serialization

* to indicate EOF during deSerialization process.

*/

class EofIndicatorClass implements Serializable{}

/*Author : AnkitMittal  Copyright- contents must not be reproduced in any form*/

class Employee implements Serializable {

   private static final long serialVersionUID = 1L;

   private String name;

   public Employee(String name) {

          this.name = name;

   }

   @Override

   public String toString() {

          return «Employee [name=» + name + «]»;

   }

}

/*

* Serialization class

*/

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class SerializeEmployee {

   public static void main(String[] args) {

          Employee object1 = new Employee( «amy»);

          Employee object2 = new Employee( «ankit»);

          try {

                 OutputStream fout = new FileOutputStream(«ser.txt»);

                 ObjectOutput oout = new ObjectOutputStream(fout);

                 System.out.println(«Serialization process has started, «

                              + «serializing employee objects…»);

                 oout.writeObject(object1);

                 oout.writeObject(object2);

                 //write instance of EofIndicatorClass at EOF

                 oout.writeObject(new EofIndicatorClass());

                 oout.close();

                 System.out.println(«Object Serialization completed.»);

          } catch (IOException ioe) {

                 ioe.printStackTrace();

          }

   }

}

/*OUTPUT

Serialization process has started, serializing employee objects…

Object Serialization completed.

*/

Program to DeSerialize object and detecting EOF without throwing EOFException >

Avoid ObjectInputStream.readObject() from throwing EOFException at End Of File in java

import java.io.EOFException;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInput;

import java.io.ObjectInputStream;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class DeSerializeEmployee {

   public static void main(String[] args) {

          InputStream fin;

          try {

                 fin = new FileInputStream(«ser.txt»);

                 ObjectInput oin = new ObjectInputStream(fin);

                 System.out.println(«DeSerialization process has started, «

                              + «displaying employee objects…»);

                  /*

                 *If oin.readObject() returns instanceof EofIndicatorClass that means

                 *it’s EOF, exit while loop and EOFException will not be thrown.

                 */

                Object obj;

                while(!((obj =  oin.readObject()) instanceof EofIndicatorClass)){

                     System.out.println(obj);

                }

                  oin.close();

          } catch (EOFException e) {

                 System.out.println(«File ended»);

          }  catch (FileNotFoundException e) {

                 e.printStackTrace();

          } catch (IOException e) {

                 e.printStackTrace();

          } catch (ClassNotFoundException e) {

                 e.printStackTrace();

          }

          System.out.println(«Object DeSerialization completed.»);

   }

}

/*OUTPUT

DeSerialization process has started, displaying employee objects…

Employee [name=amy]

Employee [name=ankit]

Object DeSerialization completed.

*/

If you note output of program EOFException wasn’t thrown, you may compare output of the program with DeSerialization done in this post where EOFException was thrown.

Summary >

So in this Exception handling java tutorial we learned what is hierarchy of java.lang. EOFException? java.lang.EOFException is a Checked (compile time) Exception in java. What is EOFException in java? Example/Programs/Scenarios where EOFException may be thrown in java. How to avoid EOFException in java?

Having any doubt? or you you liked the tutorial! Please comment in below section.

RELATED LINKS>

Most common and frequently occurring checked (compile time) and Errors in java >

  • IOException and how to solve it in java

  • EOFException in java

  • SQLException in java

  • What is java.lang.InterruptedException in java

  • when java.lang.ClassNotFoundException occurs in java

Most common and frequently occurring unchecked (runtime) in java.

  • What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and fix it

  • NumberFormatException in java

  • IndexOutOfBoundsException in java

  • When java.lang.ArrayIndexOutOfBoundsException occurs in java

  • When java.lang.StringIndexOutOfBoundsException occurs in java

  • java.lang.ArithmeticException in java — Divide number by zero

  • When dividing by zero does not throw ArithmeticException in java

  • When java.lang.IllegalStateException occurs in java

  • when java.lang.IllegalMonitorStateException is thrown in java

  • Solve java.lang.UnsupportedOperationException in java

Most common and frequently occurring Errors in java >

  • OutOfMemoryError in java

  • When java.lang.StackOverflowError occurs in java

  • Solve java.lang.ExceptionInInitializerError in java

  • How to solve java.lang.NoClassDefFoundError in java

Few More >

  • What is difference between ClassNotFoundException and NoClassDefFoundError in java

While reading the contents of a file in certain scenarios the end of the file will be reached in such scenarios a EOFException is thrown.

Especially, this exception is thrown while reading data using the Input stream objects. In other scenarios a specific value will be thrown when the end of file reached.

Example

Let us consider the DataInputStream class, it provides various methods such as readboolean(), readByte(), readChar() etc.. to read primitive values. While reading data from a file using these methods when the end of file is reached an EOFException is thrown.

import java.io.DataInputStream;
import java.io.FileInputStream;
public class EOFExample {
   public static void main(String[] args) throws Exception {
      //Reading from the above created file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:data.txt"));
      while(true) {
         char ch;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}

Runtime Exception

Hello how are youException in thread "main" java.io.EOFException
   at java.io.DataInputStream.readChar(Unknown Source)
   at SEPTEMBER.remaining.EOFExample.main(EOFExample.java:11)

Handling EOFException

You cannot read contents of a file without reaching end of the file using the DataInputStream class. If you want, you can use other sub classes of the InputStream interface.

Example

In the following example we have rewritten the above program using FileInputStream class instead of DataInputStream to read data from a file.

 Live Demo

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String[] args) throws Exception {
      //Reading data from user
      byte[] buf = " Hello how are you".getBytes();
      //Writing it to a file using the DataOutputStream
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:data.txt"));
      for (byte b:buf) {
         dos.writeChar(b);
      }
      dos.flush();
      System.out.println("Data written successfully");
   }
}

Output

Data written successfully

Following is another way to handle EOFException in Java −

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class HandlingEOF {
   public static void main(String[] args) throws Exception {
      DataInputStream dis = new DataInputStream(new FileInputStream("D:data.txt"));
      while(true) {
         char ch;
         try {
            ch = dis.readChar();
            System.out.print(ch);
         } catch (EOFException e) {
            System.out.println("");
            System.out.println("End of file reached");
            break;
         } catch (IOException e) {
         }
      }
   }
}

Output

Hello how are you
End of file reached

In this tutorial we will discuss about the EOFException in Java. This exception indicates the the end of file (EOF), or the end of stream has been reached unexpectedly. Also, this exception is mainly used by DataInputStreams, in order to signal the end of stream. However, notice that other input operations may return a special value upon the end of a stream, instead of throwing an EOFException.

The EOFException class extends the IOException class, which is the general class of exceptions produced by failed, or interrupted I/O operations. Moreover, it implements the Serializable interface. Also, it is defined as a checked exception and thus, it must be declared in a method, or a constructor’s throws clause.

Finally, the EOFException exists since the 1.0 version of Java.

The Structure of EOFException

Constructors

  • EOFException()
  • Creates an instance of the EOFException class, setting null as its message.

  • EOFException(String s)
  • Creates an instance of the EOFException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The EOFException in Java

DataInputStreams provide methods that can read primitive Java data types from an underlying input stream in a machine-independent way. An application writes data, by using the methods provided by the OutputStream class, or the DataOutputStream class.

Specifically, primitive types can be read by an application, using one of the following methods:

  • readBoolean() – Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
  • readByte() – Reads and returns one input byte.
  • readChar() – Reads two input bytes and returns a char value.
  • readDouble() – Reads eight input bytes and returns a double value.
  • readFloat() – Reads four input bytes and returns a float value.
  • readInt() – Reads four input bytes and returns an int value.
  • readLong() – Reads eight input bytes and returns a long value.
  • readShort() – Reads two input bytes and returns a short value.
  • readUnsignedByte() – Reads one input byte and returns it as a zero-extended int value. The integer value resides in the range [0, 255].
  • readUnsignedShort() – Reads two input bytes and returns them as an int value. The integer value resides in the range [0, 65535].

For a list of all available methods, take a closer look on the DataInputStream class.

The following example reads all characters from an input file:

EOFExceptionExample.java:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class EOFExceptionExample {
	
	//The name of the input file.
	private final static String FILENAME = "input.txt";
	
	private static void writeToFile() throws IOException {
		DataOutputStream out = new DataOutputStream(new FileOutputStream(FILENAME));
		
		//Write a string to the stream.
		String str = "Hello from Java Code Geeks!";
		for(int i = 0; i < str.length(); ++i)
			out.writeChar(str.charAt(i));
		
		//Close the data stream.
		out.close();
		
		return;
	}
	
	public static void main(String[] args) {
		DataInputStream input = null;
		try {
			//Write some integers to the file.
			writeToFile();
			
			// Read all characters, until an EOFException is thrown.
			input = new DataInputStream(new FileInputStream(FILENAME));
			while(true) {
				char num;
				try {
					num = input.readChar();
					System.out.println("Reading from file: " + num);
				}
				catch (EOFException ex1) {
					break; //EOF reached.
				}
				catch (IOException ex2) {
					System.err.println("An IOException was caught: " + ex2.getMessage());
					ex2.printStackTrace();
				}
			}
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			try {
				// Close the input stream.
				input.close();
			}
			catch(IOException ex) {
				System.err.println("An IOException was caught: " + ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

In this example we first, write a string to a file and then, use the readChar() method to read all written characters one-by-one.

A sample execution is shown below:

Reading from file: H
Reading from file: e
Reading from file: l
Reading from file: l
Reading from file: o
Reading from file:  
Reading from file: f
Reading from file: r
Reading from file: o
Reading from file: m
Reading from file:  
Reading from file: J
Reading from file: a
Reading from file: v
Reading from file: a
Reading from file:  
Reading from file: C
Reading from file: o
Reading from file: d
Reading from file: e
Reading from file:  
Reading from file: G
Reading from file: e
Reading from file: e
Reading from file: k
Reading from file: s
Reading from file: !

Once the EOFException is thrown, we only have to break from the reading loop and then, close the stream.

Download the Eclipse Project

This was a tutorial about the EOFException in Java.

Exception in thread «main» java.io.eofexception

In this post i am going to discuss about the End of File(EOF) exception.EOFexception extends IOException and is thrown while performing I/O operations.

This exception is usually thrown when the end of file (EOF) is reached unexpectedly while reading the input file.Note that,this exception will also be thrown if the input file contains no data in it.

I have explained this EOF exception with the following program.The following program tries to read the file «exam.txt» and prints its contents.When the reader has reached the end of the file i have thrown the EOF exception to indicate that the file has reached its end.

Program:

import java.io.*;

public class Example1
{

public static void main(String[] args)throws IOException
{
BufferedReader br=null;
try
{
File f=new File(«E:/exam.txt»);
FileReader reader = new FileReader(f);
br = new BufferedReader(reader);
String strcontent =null;
while(true)
{
if((strcontent=br.readLine()) != null)
{
System.out.println(strcontent);
}
else
{
throw new EOFException();
}
}

}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(EOFException e1)
{
br.close();
System.out.println(«The file has reached its end»);
}
}
}

Thus in the above code the statement «throw new EOFException()» is used to explicily indicate the end of the file and perform the necessary actions rather than letting jvm to deal with it.

In the above program if you do not include the statement throw new EOFException then it will not get terminated.

Sometimes this exception may occur due to an error in the input file.For eg. if the header of the file indicates that the content length of the file is 1000 characters but if you encounter the EOF character after reading some 200 characters.In this situation EOFException can be used to deal with it.

NOTE:


1.When we use Scanner object to read from a file then java.util.NoSuchElementException is thrown if the end of file (EOF) is reached.
2.If we use BufferedReader object to read from a file then no exception will be thrown upon reaching the end of the file.
3. If we use DataInputStream object to read from a file then this EOFException will be thrown if  the reader has reached the end of the file.

I have also explained, how using DataInputStream Object  to read a file throws the EOFException  in the following program.

Program:

import java.io.*;

import java.util.*;

public class Fileclassread

{

public static void main(String args[])

{

String line;

try

{

DataInputStream in=new DataInputStream(new FileInputStream(«Child1.class»));

int bytesavailable=in.available();

System.out.println(«Total no of bytes in the file «+bytesavailable);

for(int i=0;i

{

if(in.readInt()==0xCAFEBABE)

{

System.out.println(«The minor version number:»+in.readShort());

System.out.println(«The major version number:»+in.readShort());

}

}

}

catch(EOFException e)

{

System.out.println(«the file has reached its end…»);

}

catch(IOException e)

{

e.printStackTrace();

}

}

}

output:

Total number of bytes in the file 227

The minor version number:0

The major version number:50

java.io.EOFException

        at java.io.DataInputStream.readInt(Unknown Source)

        at Fileclassread.main(Fileclassread.java:18)

If you see the output of the program,the first line shows how many bytes available in the class file.

Since readInt() will read 4 bytes of data at a time,the for loop should be limited to the value of 55,

because the two readShort() contributes the other 4 bytes.So a total of 224 bytes will be read.

The remaining 3 bytes cannot be read by using readInt() as it requires 4 bytes.Thus java.io.EOFException is thrown.

Я хочу прочитать файл и если там email существует — ничего не делать, а если не существует — записать email в файл.

private void readEmail(String file, Email emails) {
    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Email email;
        while ((email = (Email) objectInputStream.readObject()) == null || (email = (Email) objectInputStream.readObject()) != null) {
            if (!emails.getEmail().equals(email)) {
                writeInFile(file, emails);
            } else {
                System.out.println("User already exist!");
            }
        }
        objectInputStream.close();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Sergey-N13's user avatar

Sergey-N13

5752 серебряных знака14 бронзовых знаков

задан 24 ноя 2018 в 22:21

Newer13's user avatar

1

Во-первых, метод readObject не возвращает null в конце файла. Он выбрасывает исключение EOFException, когда достигнут конец файла.
Ловите данное исключение и обрабатывайте его необходимым образом.

Во-вторых, вот здесь while ((email = (Email) objectInputStream.readObject()) == null || (email = (Email) objectInputStream.readObject()) != null) Вы выполняете что-то не совсем понятное. Как минимум, вы дважды вызываете метод readObject, читаете сразу два объекта из файла, переопределяете email и, как следствие, после обрабатываете лишь второй объект, теряя первый.

ответ дан 25 ноя 2018 в 14:46

justcvb's user avatar

justcvbjustcvb

1,1922 золотых знака7 серебряных знаков14 бронзовых знаков

Попробуйте добавить проверку в while

objectInputStream.available() > 0

ответ дан 25 ноя 2018 в 3:55

Ihar Hulevich's user avatar

Ihar HulevichIhar Hulevich

8056 серебряных знаков9 бронзовых знаков

I am getting error msg the EOFfile is reached and what i am doing is simply reading and writing long value which is the size of the file through socket but i got error on client side Java.io.EOFexception the code is like this
Client(Android)

try 
            {

                Log.v("read size and number", "item");
                soc = new Socket(InetAddress.getByName(ip), 3838);
                output = new ObjectOutputStream(soc.getOutputStream());
                output.writeUTF(Constants.REQUEST_SIZE_AND_NUMBER+","+path);
                output.flush();
                input = new ObjectInputStream(soc.getInputStream());
        System.out.println("size......");
                    size =  input.readLong();

            } 
            catch (UnknownHostException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         finally
         {
             closeConnection();
         }

Server

 try
{
  System.out.println("Request size.....");
                   long size = diskinfo.folderSize(new File(path));
                   System.out.println("Size of folder "+size);
                   out = new ObjectOutputStream(soc.getOutputStream());
                      out.writeLong(size);
                      out.flush();
}
 catch (IOException ex)
            {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
finally
{
  closeConnection() //closing input, output and socket
}

generated log

09-23 20:56:45.573: W/System.err(5042): java.io.EOFException
09-23 20:56:45.573: W/System.err(5042):     at java.io.DataInputStream.readShort(DataInputStream.java:375)
09-23 20:56:45.573: W/System.err(5042):     at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2388)
09-23 20:56:45.573: W/System.err(5042):     at java.io.ObjectInputStream.<init>(ObjectInputStream.java:445)
09-23 20:56:45.573: W/System.err(5042):     at com.example.diskexplorer.Client$SizeAndNumberTask.doInBackground(Client.java:138)
09-23 20:56:45.573: W/System.err(5042):     at com.example.diskexplorer.Client$SizeAndNumberTask.doInBackground(Client.java:1)
09-23 20:56:45.573: W/System.err(5042):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-23 20:56:45.573: W/System.err(5042):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-23 20:56:45.573: W/System.err(5042):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-23 20:56:45.573: W/System.err(5042):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
09-23 20:56:45.573: W/System.err(5042):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
09-23 20:56:45.573: W/System.err(5042):     at java.lang.Thread.run(Thread.java:1096)

   H A D G E H O G s

15.01.21 — 13:00

Дня доброго.

Есть МобильныйКлиент, который регулярно падает при работе с Апачем с ошибкой

«Ошибка HTTP при обращении к серверу»

Java.IO.EOFException

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

Чтобы (возможно) отловить кривой http пакет, между Apache и МобильныйКлиентом как прокси-сервер был засунут Fiddler, и, о чудо, суко, квантовый эффект, система застеснялась и ошибки прекратились.

Чем таким может отличаться подключение java компонент к Fiddler-у от подключения к Apache ?

Да, я пробовал на домашнем компе и без прокси воспроизвести ошибку с подключенным через adb к Android Studio клиентом , собранным с debugabled-ключом, чтобы словить трассу, хрен там, не воспроизводиться.

   Kassern

1 — 15.01.21 — 13:03

(0) это как квантовая физика, пока ты не наблюдатель, эффект один, как только стал наблюдать — другой))

   Вафель

2 — 15.01.21 — 13:04

клиент пытается прочитать больше чем пришло.
почему так — кто бы знал

   H A D G E H O G s

3 — 15.01.21 — 13:04

Перерыто уже все, УФ-форма выгружена в xml и 160 Кбайт XML текста просмотрено вручную, проверено на недопустимые символы, серверные вызовы переписаны на внеконтекстные, я четко знаю, что ползает между сервером и клиентов, хрен там.

В принципе, я готов уже вручную разбирать логи modsec_audit, если Fiddler мешает ошибке, проблема в том, что эти логи — это двоичные бинарные данные, которые Fiddler декодирует на раз, а modsec_audit пишет в како-то своем формате.

   H A D G E H O G s

4 — 15.01.21 — 13:05

Ну и классическое — у клиента Апач стоит на linux-е, как в нем modsec_audit настраивать — я х.з.

   polosov

5 — 15.01.21 — 13:05

(3) попробуй написать Петру Грибанову (grip@2c.ru). Он курирует разработку моб. клиента.

   H A D G E H O G s

6 — 15.01.21 — 13:06

(5) Он отправит сам знаешь куда. Если только лично.

   Вафель

7 — 15.01.21 — 13:06

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

   H A D G E H O G s

8 — 15.01.21 — 13:07

(7) Воспроизводиться у нескольких клиентов.

   Вафель

9 — 15.01.21 — 13:07

и тоже на линухе у всех?

   polosov

10 — 15.01.21 — 13:07

(6) Ну на конференции по моб. клиенту он говорил мол робяты, чокак пишите.

   H A D G E H O G s

11 — 15.01.21 — 13:10

(2) «клиент пытается прочитать больше чем пришло.»

Это ответ с сервера, Response, я правильно понимаю?

   H A D G E H O G s

12 — 15.01.21 — 13:10

(9) Нет, в основном, винда.

   H A D G E H O G s

13 — 15.01.21 — 13:11

Еще момент, если хоть один клиент подключен через прокси, ошибка прекращается на всех клиентах, даже те, которые не через прокси.

   Вафель

14 — 15.01.21 — 13:13

по идее апач говорит — сейчас вышлю 1кбайт, а высылает 100байт
прокси наверно умеет такое обрабатывать

   Вафель

15 — 15.01.21 — 13:14

тут скорее где-то на уровне тсп ошибка, не в тексте ответа

   polosov

16 — 15.01.21 — 13:14

(13) А платформа у тебя не 18.1208 случайно?

   H A D G E H O G s

17 — 15.01.21 — 13:15

Веб-сервер (Апач или Fiddler) может сам выставлять какие-то свои настройки соединения?

   H A D G E H O G s

18 — 15.01.21 — 13:15

(16) Все многообразие от 8.3.12 до 8.3.17

   H A D G E H O G s

19 — 15.01.21 — 13:16

(14) почему тогда (13) ?

   Fedor-1971

20 — 15.01.21 — 13:17

(0) похоже, что кто-то читает быстрее, чем данные поступают, а Fiddler малость тормозит процесс чтения

Чисто как предположение: разрядность appache с проблемами одинаковая?

   polosov

21 — 15.01.21 — 13:18

(19) А трафик у тебя никто подрезать не может? Fiddler возможно как-то нивелирует это.

   Fedor-1971

22 — 15.01.21 — 13:19

(19) Прокси немножко упорядочивает поступление данных, т.е. если ожидается поступление 100 КБ, он их будет ждать и потом отдаст целиком

   Fedor-1971

23 — 15.01.21 — 13:24

22+ и с остальными адресами, идёт проверка «А не за прокси ли сей адрес», соответственно и данные поступают упорядоченнее и приложение будет ждать, а не читать чего не попадя

   H A D G E H O G s

24 — 15.01.21 — 13:25

(20) Разрядность я не знаю.

(21) Да вроде нет.

Вот типовой серверный запрос

Request Count:   1

Bytes Sent:      7 046        (headers:533; body:6 513)

Bytes Received:  48 601        (headers:252; body:48 349)

ACTUAL PERFORMANCE

—————

NOTE: This request was retried after a Receive operation failed.

ClientConnected:    12:05:32.307

ClientBeginRequest:    12:50:18.445

GotRequestHeaders:    12:50:18.445

ClientDoneRequest:    12:50:18.461

Determine Gateway:    0ms

DNS Lookup:         0ms

TCP/IP Connect:    0ms

HTTPS Handshake:    0ms

ServerConnected:    12:50:18.461

FiddlerBeginRequest:    12:50:18.461

ServerGotRequest:    12:50:18.461

ServerBeginResponse:    12:50:18.461

GotResponseHeaders:    12:50:19.761

ServerDoneResponse:    12:50:19.761

ClientBeginResponse:    12:50:19.761

ClientDoneResponse:    12:50:19.761

    Overall Elapsed:    0:00:01.315

RESPONSE BYTES (by Content-Type)

—————

application/mobile+fastinfoset: 48 349

                     ~headers~: 252

   H A D G E H O G s

25 — 15.01.21 — 13:40

попробую воткнуть что-то вместо Fiddler-а

  

H A D G E H O G s

26 — 15.01.21 — 13:40

А есть какой-нибудь еще продвинутый прокси-сервер под венду?

Понравилась статья? Поделить с друзьями:
  • Ошибка в ланосе р0342 что это
  • Ошибка в лайтруме при экспорте фотографий
  • Ошибка в лайтруме assertion failed
  • Ошибка в край оф фир
  • Ошибка в кпп юридического лица