如何在从sftp下载/上传sftp时添加进度监视器

时间:2019-01-08 08:33:23

标签: java jframe sftp jprogressbar progressmonitor

我正在尝试在程序中添加进度监视器,以查看通过sftp服务器完成上载或下载操作的百分比。特别是,我想打开一个新窗口(JFrame)并在其中显示%,以及正在处理的文件的名称。

为了建立连接,我使用Jsch库。我无法弄清楚必须如何修改代码的哪一部分。我试图添加一个JProgress监视器,但是我不知道在哪里插入它,因为我有一个for循环。我尝试插入SwingWorker,但仅找到System.out.println的示例,而不是“图形”方式。这是我的代码的一部分:

public void connect(String host, String user, String pwd, int port) throws JSchException, SftpException, IOException {

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(user, host, port);            
        session.setPassword(pwd);                   
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();                                      
        sftpChannel = (ChannelSftp) session.openChannel("sftp");    
        sftpChannel.connect();                                                  
    } catch(JSchException | SftpException e) {                      
        JOptionPane.showMessageDialog(null, "ERROR!");
    JLabel label = new JLabel("ERROR! ");
    contentPane.add(label, BorderLayout.NORTH);
        System.out.println(e);
    }    
}


public void downloadFile() {
    UIManager.put("ScrollPane.background", Color.BLACK);
    UIManager.put("List.background", Color.WHITE);
    UIManager.put("List.foreground", Color.BLACK);
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) {
        e1.printStackTrace();
    }

    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Browse the folder to process");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

   if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
       path = new File(chooser.getSelectedFile().getAbsolutePath());
       pathName = path.toString();      

        dwnPending =true;
       for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.

           currentFileDownload= oListItem.getFilename();

           segnaLista = segnaLista - 1;
        try {
                sftpChannel.get("pub/example/" + currentFileDownload, pathName);        
            } catch (SftpException e) {
                JOptionPane.showMessageDialog(null, "Impossible to download the file " + currentFilDownload+ ". SFTP error. The file will not be removed from the server");
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Impossibile to download file " + currentFilDownload);
            }
       dwnPending =false;
       JOptionPane.showMessageDialog(null, "Download completed in: " + pathName);   
    } 
}

我想以最简单的方式实现它。只是大致了解传输何时完成。

0 个答案:

没有答案