我想在下载之前获取文件大小,以便我可以将它用于进度条。我发现这个Post但无法确定获取文件大小的确切命令.Plz帮助!!
答案 0 :(得分:0)
JSch已经提供SftpProgressMonitor
来监控上传和下载进度。它有三个函数,其中一个init
将为您提供远程文件大小。我准备了一个小程序,您可以根据需要直接使用或自定义。
<强> 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");
}
}
在您的实施课程中,请使用以下
ChannelSftp sftp = null; // initiate this channel
sftp.get(remoteFileName,
destDir,
new DownloadProgressMonitor(),
ChannelSftp.OVERWRITE);
这将无需任何其他代码即可使用。