java code to download a file from server

2019-01-23 00:15发布

问题:

using java code in windows i need to download several files from a directory placed in a server. those files in server 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.

回答1:

Use java.net.URL and java.net.URLConnection classes.



回答2:

  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...



回答3:

You can use HttpURLConnection to download file over HTTP, HTTPS



回答4:

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.



回答5:

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



回答6:

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.