The following code used to run under Java 6 (and earlier) stopped working after upgrading to JRE 7 (Java 7).
FTP File URL:
ftp://ftp-private.ncbi.nlm.nih.gov/pubchem/.fetch/96/4133257873201306969.sdf.gz
Here is the result I get:
applications / octet stream -1 [Ljava.lang.StackTraceElement; @ 5419f97c
And here is my code:
public static void store(URL url, File targetFile){ try { System.out.println(url); URLConnection uc = url.openConnection(); String contentType = uc.getContentType(); System.out.println(contentType); int contentLength = uc.getContentLength(); System.out.println(contentLength); Settings.setDownloadSize(contentLength); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); } InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; StatusPanel.updateProgrssBar(bytesRead); int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) { break; } offset += bytesRead; StatusPanel.updateProgrssBar(offset); } in.close(); if (offset != contentLength) { throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); } FileOutputStream out = new FileOutputStream(targetFile); out.write(data); out.flush(); out.close();
The length of the content returns -1:
Area: API: Networking Synopsis: Server Connection Shuts Down when Attempting to Read Data When http Response Code is -1
How do I make this code compatible with Java 7?
Description. As a result of error correction for CR 6886436, the HTTP protocol handler will close the connection to the server, which sends the response without a valid HTTP status bar. When this happens, any attempt to read data on this connection throws an IOException.
For example, the following code is problematic:
public static void test () throws Exception { ..... HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); .... System.out.println ("Response code: " + urlc.getResponseCode()); InputStream is = urlc.getInputStream();
To work around this problem, check the return value from the getResponseCode method and process the -1 value accordingly; possibly by opening a new connection or calling getErrorStream in a stream. Incompatibility Nature: Behavioral RFE: 7055058
The problem is definitely with the getContentLength() method.
With JRE6, this method returns a value, but with JRE7 I get -1.