using java code in windows i need to download several files from a directory placed in a server. those files in serve开发者_如何学运维r are generated separately. so i'll not know the name of those files. is there any way to download it using JAVA and saving it in a specific folder.
i am using apache tomcat.
I read all other threads related to java file download. But none of them satisfy my requirement.
try {
// Get the directory and iterate them to get file by file...
File file = new File(fileName);
if (!file.exists()) {
context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
context.setForwardName("failure");
} else {
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition", "attachment"+
"filename=" + file.getName());
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope you got some idea...
Use java.net.URL
and java.net.URLConnection
classes.
Hi you can use this following code snippet to down the file directly :
URL oracle = new URL("http://www.example.com/file/download?");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Kindly refer about openStream in this [URL] : http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
You can use HttpURLConnection
to download file over HTTP, HTTPS
It is only possible if server lists directory contents. if it does, your can make an HTTP request to:
http://server:port/folder
that would give you list of files.
Once you have that, you can download individual files by parsing output if this http request.
If it is server, then the process must be like using the FTP credentials you have to dosnload the files. This java file download example may help you.
精彩评论