I want to get the File size before downloading it so that i can use it for Progress Bar.I found this Post but couldn't figure out the exact command to get the file size .Plz Help !!
Asked
Active
Viewed 2,133 times
0
-
It looks like the answer is right there in that answer. What happened when you tried to use the suggested code? – Duncan Jones Mar 25 '14 at 10:58
-
@Duncan : SftpATTRS was not available in my Jasch JAR – Shashank Vivek Mar 25 '14 at 12:02
1 Answers
0
JSch has already provided SftpProgressMonitor
to monitor the upload as well as download progress. It has three functions and one of these init
will give you a remote file size. I have prepared a small program which you could directly use or customize as per your need.
IOUtil.java
public final class IOUtil {
private IOUtil() {}
public final DecimalFormat PERCENT_FORMAT = new DecimalFormat("#.##");
private static final double KB = 1024.0d;
private static final double MB = KB * 1024.0d;
public static String getFileSize(final long fileSize) {
if (fileSize < KB) {
return fileSize + " bytes";
} else if (fileSize < MB) {
return DECIMAL_FORMAT.format((fileSize / KB)) + " KB";
} else
return DECIMAL_FORMAT.format((fileSize / MB)) + " MB";
}
public static String calculatePercent(double part, double whole) {
return PERCENT_FORMAT.format ((part / whole) * 100);
}
}
DownloadProgressMonitor.java
public class DownloadProgressMonitor implements SftpProgressMonitor {
private double bytesCopied = 0L;
private double fileSize = 0L;
private String src;
private String dest;
public DownloadProgressMonitor() {
IOUtil.PERCENT_FORMAT.setRoundingMode(RoundingMode.CEILING);
}
@Override
public void init(int operation, String src, String dest, long fileSize) {
this.fileSize = Double.parseDouble(fileSize + "");
this.src = src;
this.dest = dest;
System.out.println("Downloading file: " + src + " (" + IOUtil.getFileSize(fileSize) + ")...");
}
@Override
public boolean count(long bytesTransferred) {
bytesCopied += bytesTransferred;
// watch out this is only print not println
System.out.print(IOUtil.calculatePercent(bytesCopied, fileSize) + "%...");
return bytesTransferred != 0;
}
@Override
public void end() {
System.out.println(src + " downloaded \n");
}
}
In your implementation class please use as follow
ChannelSftp sftp = null; // initiate this channel
sftp.get(remoteFileName,
destDir,
new DownloadProgressMonitor(),
ChannelSftp.OVERWRITE);
This will work without any additional code.

Adi
- 57
- 1
- 9