problem in downloading file from a URL.
Hi All,
I have a file on my local server tomcat.
I am trying to save this file to different location in my computer using a servlet . Servlet reads the file from the URL and writes to some location.
Here is the code.
Code:
HttpURLConnection connection = null;
//OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
URL serverAddress = null;
try {
serverAddress = new URL("http://localhost:8080/data/video.flv");
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
Writer output = new BufferedWriter(new FileWriter("/home/lalit/file.flv"));
System.out.println(connection.getContentLength());
int length = connection.getContentLength();
int contentLength = connection.getContentLength();
char buffer[] = new char[contentLength];
output.write(buffer, 0, contentLength);
output.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
rd = null;
connection = null;
}
This successfully saves file at specified location but i am not able to open this file. I tried different file formats flv, 3GP, doc etc.
Thanks