FTP apache commons progress bar in java
Asked Answered
S

1

5

I'm working on a little program, which can upload a file to my FTP Server and do some other stuff with it. Now... It all works, i'm using the org.apache.commons.net.ftp FTPClient class for uploading.

ftp = new FTPClient();
ftp.connect(hostname);
ftp.login(username, password);

ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/shares/public");
int reply = ftp.getReplyCode();

if (FTPReply.isPositiveCompletion(reply)) {
    addLog("Uploading...");
} else {
    addLog("Failed connection to the server!");
}

File f1 = new File(location);
in = new FileInputStream(

ftp.storeFile(jTextField1.getText(), in);

addLog("Done");

ftp.logout();
ftp.disconnect();

The file which should uploaded, is named in hTextField1. Now... How do i add a progress bar? I mean, there is no stream in ftp.storeFile... How do i handle this?

Thanks for any help! :)

Greetings

Stanley answered 9/3, 2013 at 10:17 Comment(0)
E
32

You can do it using the CopyStreamListener, that according to Apache commons docs is the listener to be used when performing store/retrieve operations.

CopyStreamAdapter streamListener = new CopyStreamAdapter() {

    @Override
    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
       //this method will be called everytime some bytes are transferred

       int percent = (int)(totalBytesTransferred*100/yourFile.length());
       // update your progress bar with this percentage
    }

 });
ftp.setCopyStreamListener(streamListener);

Hope this helps

Eolith answered 9/3, 2013 at 11:8 Comment(3)
Oh, thank you so much, that works! But now i got another problem... If i press on the button which uploads the file, the program freezes, and if the upload is done the full progressbar is full...Stanley
That's because you do the upload in the GUI thread, so the GUI freezes, and waits for your upload to be done, a way to avoid that is using Threads, there is an example: Thread ExampleEolith
After hours of searching, finally found a solution that worked for me. +1! Thanks @BackSlash!Vonnie

© 2022 - 2024 — McMap. All rights reserved.