简体   繁体   中英

Java ftp download status bar

Hello i need a status bar for FTP download. I would like to get a float <=1 with the progess. This is my code:

                float status=0;
                FTPFile[] files = ftp.listFiles(REMOTEFILE);
                if (files == null || files.length == 0) {
                    throw new FileNotFoundException();
                }
                long size = files[0].getSize();
                InputStream inputStream = ftp.retrieveFileStream(REMOTEFILE);
                byte buf[] = new byte[1024];
                int len;
                int download=0;
                while ((len = inputStream.read(buf)) > 0){
                    out.write(buf, 0, len);
                    download+=1024;
                    status=(float)download/size; // here it set the progress
                }
                out.close();

My trouble is that at the end status is more than 1 and I think is over the buffer size of 1024 (in case of not full buffer at the end). Maybe because downloaded bytes are more than how much files[0].getSize() gives to me?

Thank you.

You add 1024 bytes to download no matter how many bytes are actually read. You already have a ref to the number of bytes read; len - use this instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM