3

I am using apache commons-net for downloading a file from an FTP server. That much is working fine. The part I am having a problem with is showing the download progress using a JProgressBar.

The following code demonstrates how I am downloading the file I need:

public void download() {
    try {
        FTPClient ftpClient = new FTPClient();

        String fileName = "OFMEX_MANUFACTURING.jar";

        ftpClient.connect("192.168.1.242");
        int replyCode = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            JOptionPane.showMessageDialog(null, "Server Down");
        }

        boolean login = ftpClient.login("bioftp", "bioftp");

        boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory("ofmex\\Linux\\");
        boolean setFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpClient.enterLocalPassiveMode();

        OutputStream data = (OutputStream) new FileOutputStream(fileName);

        ftpClient.retrieveFile(fileName, data);
        ftpClient.abort();               
    } catch (Exception e) {
        e.printStackTrace();
    }
} 
Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
Harsha
  • 3,548
  • 20
  • 52
  • 75

3 Answers3

2

You should be able to use a CopyStreamListener. Note that the bytesTransferred(CopyStreamEvent event) method is not used, but the bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) should be.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
2

If You are going to call retriveFile() directly then you may not be able to know how many bytes are transferred. Instead, you can retrieve a file byte by byte and keep count of every byte transferred. You can also get the total bytes to be transferred so that you can calculate a percentage to show in the progress bar.

InputStream stSource = new FileInputStream(locFile);
OutputStream stDest = new BufferedOutputStream(ftp.storeFileStream(remFile), ftp.getBufferSize());

Util.copyStream(stSource, stDest, ftp.getBufferSize(),CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamAdapter() {
    public void bytesTransferred(long totalBytesTransferred,int bytesTransferred, long streamSize) {
        long megsTotal = 0;
        long megs = totalBytesTransferred / 1048576;

        for (long l = megsTotal; l < megs; l++) {
            System.err.print("|");
        }

        megsTotal = megs;
    }
});

See this apache commons util used in above code.

Liam George Betsworth
  • 18,373
  • 5
  • 39
  • 42
JAVAGeek
  • 2,674
  • 8
  • 32
  • 52
0

In NetBeans create a Desktop application. It gives yous a pre-built progressbar with task monitor and busy icons and everything you need. Use CopyStreamListener and use bytesTransferred method to manage the progressbar.

Sree
  • 746
  • 6
  • 21