- java.io.EOFException: at java.io.DataInputStream.readUTF (Неизвестный источник) — запись файла построчно
- 2 ответа
- readUTF not working
- Saved searches
- Use saved searches to filter your results more quickly
- EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream #1517
- EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream #1517
- Comments
- Русские Блоги
- эксперимент
- решение
java.io.EOFException: at java.io.DataInputStream.readUTF (Неизвестный источник) — запись файла построчно
Я сделал простое приложение «сервер-клиент», чтобы построчно читать файл с сервера и построчно записывать новый файл на стороне клиента. Приложение корректно записывает строки в файл, но когда файл подходит к концу, я улавливаю эту ошибку:
java.io.EOFException at java.io.DataInputStream.readUnsignedShort(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at it.sendfile.socket.FileClient1.main(FileClient1.java:19)
public class FileServer1 < public static void main(String[] args) < int port = 3000; // open server socket ServerSocket ss = null; try < ss = new ServerSocket(port); Socket s = ss.accept(); DataOutputStream outToClient = new DataOutputStream(s.getOutputStream()); File testFile = new File("C:\\temp\\tmpbgoutcoge"); BufferedReader input = new BufferedReader(new FileReader(testFile)); String line; while ((line = input.readLine()) != null) < outToClient.writeUTF(line); outToClient.writeUTF("-----------------------------"); outToClient.flush(); Thread.currentThread().sleep(1000); >input.close(); outToClient.close(); s.close(); > catch (Exception e) < System.out.println(e.getMessage()); >> > public class FileClient1 < public static void main(String[] args) < try (PrintWriter out = new PrintWriter(new FileWriter("C:\\temp\\tmpbgoutcoge1.txt", true));) < Socket s = new Socket("localhost", 3000); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(s.getInputStream())); while (true) < String line = inFromServer.readUTF(); System.out.println(line); out.write(line); out.println("\n"); >> catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
Мне нужно найти условие «Остановить время», когда я достигну конца файла, но я попытался (line = inFromServer.readUTF ())! = Null, но это не сработало. В классе FileClient1 я не могу закрыть сокет и DataInputStream. Сообщение гласит: «Недоступный код».
2 ответа
ReadUTF () никогда не вернет ноль. Перед закрытием необходимо отправить «значение часового» — специальное значение, указывающее конец потока.
Очевидно, вы хотите, чтобы это было что-то, что вряд ли будет отправлено в обычном случае использования. Я предлагаю «\uffff» (строка длиной 1), поскольку U + FFFF гарантированно не будет определенным символом.
while(inFromServer.available()>0)
readUTF not working
posted 13 years ago
i am reading char data from a text file in utf format.
here is the code
if i don’t use readUTF (i used readLine in order to check by the way), then there is no problem , it goes OK, but when i use readUTF, the it throws EOFException. why is that??
java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:180)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at mainclient.FileInput.main(FileInput.java:49)
BUILD SUCCESSFUL (total time: 1 second)
Java Cowboy
posted 13 years ago
- 1
Class DataInputStream is the wrong thing to use when reading from a text file. As the documentation says, class DataInputStream is meant for reading primitive Java data types from an underlying input stream, and readUTF() uses some kind of modified UTF-8 format (not the standard UTF-8 format).
For reading from text files, you should use a Reader. The various Reader classes that exist in java.io (for example BufferedReader, InputStreamReader, FileReader etc.) take care of converting data from an input stream to text, using a character encoding.
To read a text file in UTF-8 encoding, try this:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream #1517
EOFException in RealBufferedSource.readUtf8LineStrict(): 0-bytes in stream #1517
Comments
We’re getting an EOF exception with size=0 in the stream.
java.io.EOFException: \n not found: size=0 content=. at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200) at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:187) at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80) at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:791) at com.squareup.okhttp.internal.http.HttpEngine.access$200(HttpEngine.java:90)
The text was updated successfully, but these errors were encountered:
@simtse what device are you using?
We are using Nexus 4, Nexus 5, Samsung Galaxy S4, Galaxy Note 3, OnePlus One, Nexus 9, HTC One M7, HTC One S, HTC One One X, Moto X 2013. Those are the ones we use most often.
Getting this issue on Huawei P6-U06 4.2.2. The problem seems to appear quite often only while downloading large files e.g. 600 Mb. The only solution is to make a connection retry?(
I’am using a GET request.
I am facing this issue during low traffic time, I have 24 threads connected to the influxdb server making batch/sec updates. Little insight might help.
Caused by: retrofit.RetrofitError: unexpected end of stream on Connection (recycle count=0)
at retrofit.RetrofitError.networkError(RetrofitError.java:27)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:395)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at org.influxdb.impl.$Proxy5.write(Unknown Source) ~[na:na]
at org.influxdb.impl.InfluxDBImpl.write(InfluxDBImpl.java:126)
at
. 21 common frames omitted
Caused by: java.io.IOException: unexpected end of stream on Connection (recycle count=0)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:211)
at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:917)
at com.squareup.okhttp.internal.http.HttpEngine.access$300(HttpEngine.java:95)
at com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:902)
at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:760)
at com.squareup.okhttp.Call.getResponse(Call.java:274)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:230)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:201
at com.squareup.okhttp.Call.execute(Call.java:81)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
. 25 common frames omitted
Caused by: java.io.EOFException: \n not found: size=0 content=.
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
. 36 common frames omitted
Are you aware of any workaround possible? The issue doesn’t seem to happen on Android 5.0.2, but happens quite often on 4.1.2 and 4.1.4 (at least).
Same issue here,
IOException is thrown in 3 ms every 10, 20 or 30 requests .
OkHttpClient client = new OkHttpClient();
client.setRetryOnConnectionFailure(false);
HttpURLConnection connection = new OkUrlFactory(client).open(url);
It never happens with okhttp include in Lollipop.
Running into this issue? Please send me a test case!
I recreated this issue on OkHttp 2.4.0 in debug. I set a break point on the line «Response response = getResponse().getResponse();» in the HttpURLConnectionImpl# getHeaders() method. My tomcat server is configured connectionTimeout=»10000″ for SSL connector. So, if I hold the getHeaders() method and let the server to close the connection. The client side always complains:
«org.springframework.web.client.ResourceAccessException: I/O error on POST request for «https://xxx.xxx.xxx.xxx/myapplication/api/myservice»: unexpected end of stream on Connection (recycle count=3); nested exception is java.io.IOException: unexpected end of stream on Connection (recycle count=3)
.
Caused by: java.io.IOException: unexpected end of stream on Connection (recycle count=3)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:211)
at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:917)
at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:793)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:439)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getHeaders(HttpURLConnectionImpl.java:150)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getHeaderFieldKey(HttpURLConnectionImpl.java:202)
at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.getHeaderFieldKey(DelegatingHttpsURLConnection.java:202)
at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.getHeaderFieldKey(HttpsURLConnectionImpl.java:25)
at org.springframework.http.client.SimpleClientHttpResponse.getHeaders(SimpleClientHttpResponse.java:92)
. 9 common frames omitted
Caused by: java.io.EOFException: \n not found: size=0 content=.
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
. 27 common frames omitted
I cannot image any reason that would cause the client spend more than 10s to read the response. Any idea?
@dmoneyUK could you isolate this into a test case? There’s lots of examples in CallTest , and MockWebServer is pretty capable around setting up timeouts etc.
Русские Блоги
Выяснилось, что файл можно загрузить в обычном режиме, но после завершения загрузки возникает исключение.
эксперимент
Автор провел еще один эксперимент: сервер использует цикл для чтения информации о клиенте, а клиент отправляет данные.
// Сервер import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerTest public static void main(String[] args) new Thread(new Server()).start();; > private static class Server implements Runnable private ServerSocket ss = null; @Override public void run() try ss = new ServerSocket(6677); while(!Thread.currentThread().isInterrupted()) Socket s = ss.accept(); Thread t = new Thread(new Client(s)); t.setDaemon(true); t.start(); > > catch (IOException e) e.printStackTrace(); > > > private static class Client implements Runnable private Socket s = null; private DataInputStream dis = null; private DataOutputStream dos = null; public Client(Socket s) this.s = s; try this.dis = new DataInputStream(s.getInputStream()); this.dos = new DataOutputStream(s.getOutputStream()); > catch (IOException e) e.printStackTrace(); > > @Override public void run() try while(!Thread.currentThread().isInterrupted()) String str = dis.readUTF(); System.out.println(str); > > catch (IOException e) e.printStackTrace(); >finally try if(dos!=null)dos.close(); if(dis!=null)dis.close(); if(s!=null)s.close(); > catch (IOException e) e.printStackTrace(); > > > > > // Клиент import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class Test public static void main(String[] args) Socket s = null; DataOutputStream dos = null; try s = new Socket("127.0.0.1",6677); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("hello"); dos.flush(); BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream()); bos.close(); /* try < Thread.sleep(10000); >catch (InterruptedException e) < e.printStackTrace(); >*/ > catch (UnknownHostException e) e.printStackTrace(); > catch (IOException e) e.printStackTrace(); >finally try if(dos!= null) dos.close(); > if(s != null) s.close(); > > catch (IOException e) e.printStackTrace(); > > > >
Обнаружено, что исключение в описании проблемы все еще возникает.
решение
Клиент не может напрямую вызвать close () потока после отправки файла. Независимо от того, является ли это DataOoutputStream, ObjectOutputStream, BufferedOutputStream или InputStream, он не может напрямую вызвать метод close (). Когда Socket.InputStream или Socket.OutputStream вызывает close ( ) Метод сделает Socket недействительным, и сервер выдаст исключение.
С другой стороны, когда другие потоки сокета вызывают метод close (), будет вызываться метод close () потока Socket.
Поэтому, когда потоки ввода и вывода израсходованы, их не следует закрывать вовремя.Поток может быть закрыт, когда клиент закрыт или когда нужно закрыть Socket.