FTP使用进度条使用Util.copyStream - JAVA

时间:2013-09-20 02:56:12

标签: java upload ftp

我正在使用Util.copyStream()通过FTP上传文件。它显示了progressBar的进度,但是当我尝试通过FTP客户端(例如FileZilla)查看文件时,它不在那里。任何人都可以帮助我吗?

这是FTPUpload类:

    package restrictedareamanager;

    import java.awt.HeadlessException;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.swing.JOptionPane;
    import javax.swing.SwingWorker;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPReply;
    import org.apache.commons.net.io.CopyStreamAdapter;
    import org.apache.commons.net.io.CopyStreamEvent;
    import org.apache.commons.net.io.CopyStreamListener;
    import org.apache.commons.net.io.Util;

    public class FTPUploader extends SwingWorker <Object,Object> {

        private String servidor;
        private String usuario;
        private String senha;
        private String titulo;
        private String subtitulo;
        private File dest;

    public FTPUploader (String servidor, String usuario, String senha, String titulo, String subtitulo, File dest) {

        this.servidor = servidor;
        this.usuario = usuario;
        this.senha = senha;
        this.titulo = titulo;
        this.subtitulo = subtitulo;
        this.dest = dest;

    }   

    @Override
    protected Object doInBackground() throws Exception {

    FTPClient ftp = new FTPClient ();
    final ProgressBar bar = ProgressBar.getInstancia();   

                try {  
                 ftp.connect(servidor);  

                 //verifica se conectou com sucesso!  
                 if( FTPReply.isPositiveCompletion( ftp.getReplyCode() ) ) {  
                     ftp.login (usuario, senha);  
                 } else {  
                     //erro ao se conectar  
                     ftp.disconnect();  
                     JOptionPane.showMessageDialog(null, "Ocorreu um erro ao se conectar com o servidor FTP", "Erro", JOptionPane.ERROR_MESSAGE);    
                     System.exit(1);  
                 }  

                     ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                     ftp.changeWorkingDirectory("/download");
                     ftp.changeWorkingDirectory(this.titulo);
                     ftp.changeWorkingDirectory (this.subtitulo);

                     bar.setLabel1("Sending " + dest.getName());
                     bar.setLabel2("To " + this.servidor + "/download" + "/" + titulo + "/" + subtitulo);
                     bar.setLabel3 ("Progress: ");

                     OutputStream output = new BufferedOutputStream(ftp.storeFileStream(dest.getName().toString()));
                     CopyStreamListener listener = new CopyStreamListener() {

                            @Override
                            public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
                            setProgress((int) Math.round(((double) totalBytesTransferred / (double) streamSize) * 100d));
                            }

                            @Override
                            public void bytesTransferred(CopyStreamEvent arg0) {
                            // TODO Auto-generated method stub
                            }

                      };

                        Util.copyStream(new FileInputStream(dest), output , ftp.getBufferSize(), dest.length(), listener);
                        //ftp.storeFile (dest.getName(), new FileInputStream (dest.getPath().toString()));
                        ftp.logout();
                        ftp.disconnect(); 

                 } catch( IOException | HeadlessException e ) {  
                     JOptionPane.showMessageDialog(null, "Ocorreu um erro ao enviar o arquivo.", "Erro", JOptionPane.ERROR_MESSAGE);  
                     System.exit(1);
                 } catch (Exception e) {
                     System.out.println (e.toString());
                 }


       bar.dispose();
       return null;
    }

    }

1 个答案:

答案 0 :(得分:0)

storeFileStream的JavaDocs表示您必须在完成后关闭流。我不这样做。这可能是一个很好的起点。除了相当冗长之外,您的代码看起来非常可靠。

我不使用监听器或流,但是我一直使用这段代码使用FTP发送文件并且它可以工作。

请注意,ftpFTPClient

的实例
/**
 * Transmits a file to the FTP server
 * @param filePath The location on the server to place the file
 * @param data The contents of the file
 * @return True if the operation completes successfully, false otherwise
 */
public boolean send(String filePath, byte[] data)
{
    if(isConnected() == false)
    {
        logger.log(Level.WARNING, "Attempting operation when not connected to FTP Server");
        return false;
    }

    try 
    {
        boolean success =  ftp.storeFile(filePath, new ByteArrayInputStream(data));
        if(success)
        {
            logger.log(Level.FINEST, "Succesfully transmitted file: " + filePath);
            return true;
        }
        else
        {
            logger.log(Level.WARNING, "Could not transmit file: " + filePath);
            logger.log(Level.WARNING, getLastReply());
            return false;
        }
    } 
    catch (IOException ex) 
    {
        logger.log(Level.SEVERE, "Could not transmit file: " + filePath, ex);
        return false;
    }
}