Bootstrap FreeKB - Java - Download a file in Java using Eclipse
Java - Download a file in Java using Eclipse

Updated:   |  Java articles

Create a Dynamic Web Project in Eclipse. Let's say the name of the project is downloadFile.

In the left panel of Eclipse, at the name of your project (downloadFile in this example) > Java Resources > src, create a new package. For the sake of this tutorial, let's name the package com.download.file.

In the package, create a class called download.

In download.java, add the following markup.

package com.download.file;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class download{
    public String downloadFile() {    
        String result = "";
        try {
            String urlString     = "http://www.example.com/foo.txt";
            // Linux target
            String destination   = "/tmp/foo.txt";
            // Windows target
            String destination   = "C:\\Users\\JohnDoe\\Documents\\foo.txt";
            URL website          = new URL(urlString);
            ReadableByteChannel rbc;
            rbc                  = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(destination);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
            response = "Success"
        } catch (IOException e) {
            e.printStackTrace();
            response = "Failed"
        } finally {
          if (fos != null) {
            result = "Successfully downloaded foo.txt from http://www.example.com";
          }
          else {
            result = "Failed to download foo.txt from http://www.example.com";
          }
        }
        System.out.println(result);
        return result;
    }
}

 

In the left panel of Eclipse, right click on the name of your project (downloadFile in this example) and select New JSP File. Select the WebContent folder, give the file a name such as index.jsp, and select Finish.

Add the following to line 1 of the JSP file. This is the combination of the package (com.download.file) and the class (download.java).

<%@page import="com.download.file.download"%>

 

Add the following inside the <body> tags.

  • In this example, "download" must be used because the name of the class in download.java is connect.
  • In this example, "downloadFile" must be cause because the name of the method in download.java is downloadFile.
<body>
<%
  download foo = new download();
  out.println(foo.downloadFile());
%>
</body>

 

Select the green play button in Eclipse, and the file should be downloaded.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f84bc2 in the box below so that we can be sure you are a human.