Tuesday, 6 August 2013

IOException when downloading file

IOException when downloading file

Here is my simple code to download a file:
InputStream input = null;
OutputStream output = null;
try {
URL fileURL = new URL(f.getVideoURL());
URLConnection con = fileURL.openConnection();
lengthOfContent = con.getContentLength();
con.setConnectTimeout(10 * 1000);
con.connect();
input = new BufferedInputStream(fileURL.openStream());
File f = new File("/sdcard/",fileName);
if(!f.exists()){
f.createNewFile();
}else{
f.delete();
f.createNewFile();
}
output = new FileOutputStream(f);
Log.v("FILE", fileName);
byte[] data = new byte[2 * 1024];
long tempBytesWritten = 0;
while((tempBytesWritten=input.read(data))!=-1){
bytesWritten.addAndGet(tempBytesWritten);
output.write(data,0,(int)tempBytesWritten);
synchronized(h){
h.post(new Runnable(){
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
output.flush();
output.close();
input.close();
}
Although I connect using con.connect(), it says that BufferedInputStream
is not open.
How do I make sure that it is open ??

No comments:

Post a Comment