Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java code to download a file from server

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.

like image 589
su03 Avatar asked Mar 17 '11 06:03

su03


People also ask

How do I download a file in Java?

We can use java. net. URL openStream() method to download file from URL in java program. We can use Java NIO Channels or Java IO InputStream to read data from the URL open stream and then save it to file.

How do I download a file from an HTTP server?

Generally, downloading a file from a HTTP server endpoint via HTTP GET consists of the following steps: Construct the HTTP GET request to send to the HTTP server. Send the HTTP request and receive the HTTP Response from the HTTP server. Save the contents of the file from HTTP Response to a local file.

How do I download a file from REST API?

Enter the URL of the REST Service (f.e. http://localhost:8080/rest-file-manager/resr/file/upload ) Select POST as method. Select form-data in the Body. Enter as key “attachment” of Type File.


2 Answers

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

like image 97
Mohamed Saligh Avatar answered Oct 06 '22 10:10

Mohamed Saligh


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

like image 28
KV Prajapati Avatar answered Oct 06 '22 08:10

KV Prajapati