Reputation: 484
I have some Java code which reads a gzip file from an URL and decompress it. How do I make sure that the whole file is read from the connection or how do I make sure that there are no problem with it?
try {
URL url = new URL("http://example.com/de?Debug=1");
URLConnection myUrlConnection = url.openConnection();
GZIPInputStream gZIPInputStream = new GZIPInputStream(myUrlConnection.getInputStream());
StringBuffer decompressedStringBuffer = new StringBuffer();
int bytes_read;
while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {
String part = new String(buffer, 0 ,bytes_read, "UTF-8");
decompressedStringBuffer.append(part);
}
gZIPInputStream.close();
String decompressedString = decompressedStringBuffer.toString();
...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The try-catch block are auto-generated by IntelliJ. What other types of exceptions should I catch to cover : connection break
, partial data received
, connection timeout
. These are all the problems I could think of. Can you think of others?
Upvotes: 0
Views: 69
Reputation: 310985
If you get to the point where read()
returns -1 you have the entire file that was sent.
But don't collect it in memory: do something useful with it each time you get a piece: i.e. send it on, or write it to a file, or whatever.
You don't need to catch any more exceptions, and any IOExceptions
indicate trouble of one kind or another.
Upvotes: 3