简体   繁体   English

使用Jsch从Unix远程服务器获取文件大小

[英]Getting File size fron Unix remote server using Jsch

我想在下载文件之前获取文件大小,以便我可以将其用于进度栏。我找到了这篇文章,但无法弄清楚获取文件大小的确切命令。请帮助!

JSch has already provided SftpProgressMonitor to monitor the upload as well as download progress. JSch已经提供了SftpProgressMonitor来监视上传和下载进度。 It has three functions and one of these init will give you a remote file size. 它具有三个功能,其中一个init将为您提供远程文件大小。 I have prepared a small program which you could directly use or customize as per your need. 我准备了一个小程序,您可以根据需要直接使用或自定义它。

IOUtil.java 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 下载ProgressMonitor.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. 这将无需任何其他代码即可工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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