我正在使用 Util.copyStream() 通过 FTP 上传文件。它在进度条上显示进度,但是当我尝试通过 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;
}
}