-3

Downloaded Zip files using Java, when it's open saying that Can't open. Want to know what is the pblm? Is it because of less memory?

Here is the code for downloading zipFiles

try {
    for(int i=0;i<URL_LOCATION.length;i++) {
        url = new URL(URL_LOCATION[i]);
        connection = url.openConnection(); 
        stream = new BufferedInputStream(connection.getInputStream());
        int available = stream.available();
        b = new byte[available];
        stream.read(b);
        File file = new File(LOCAL_FILE[i]);
        OutputStream out  = new FileOutputStream(file);
        out.write(b);
        }
} catch (Exception e) {
    System.err.println(e.toString());
}

Soln for this: Refered Link is How to download and save a file from Internet using Java?

BufferedInputStream in = null;
FileOutputStream fout = null;
try
{                                                                                                 
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
 fout.write(data, 0, count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}   
Community
  • 1
  • 1
raja
  • 57
  • 9

1 Answers1

2

You are using the available()-call to determine how many bytes to read. Thats blatantly wrong (see javadoc of InputStream for details). available() only tells you about data immediately available, not about the real stream length.

You need a loop and read from the stream until it return -1 (for EndOfStream) as number of bytes read.

I recommend you review the tutorial on streams: http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

Durandal
  • 19,919
  • 4
  • 36
  • 70
  • No tried that too. Not working. Why downloaded zip files are corrupted? Not able to open? – raja Jan 17 '14 at 05:22