Java code to download a file from the server

using java code in windows I need to download several files from a directory hosted on the server. these files on the server are generated separately. therefore, I will not know the name of these files. Is there any way to download it using JAVA and save it in a specific folder.

I am using apache tomcat.

I read all other topics related to downloading a java file. But none of them satisfy my requirements.

+5
source share
6 answers

Use classes java.net.URLand java.net.URLConnection.

+2
source
  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 have an idea ...

+8
source

HttpURLConnection HTTP, HTTPS

+2

, . , HTTP-:

http://server:port/folder

.

, , HTTP-.

+2

, :

    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();

openStream [URL]: http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

+2

, FTP, . java .

+1
source

All Articles