我想使用 FTP 通过 Java 应用程序上传文件,但它不起作用。
问题是,如果我在主类中执行 FTPUploader 类,它可以完美运行,但如果我喜欢它在这里,它就不起作用。你们能帮帮我吗?
我的代码是:
主线:
package restrictedareamanager;
import java.io.File;
import java.io.IOException;
public class RestrictedAreaManager {
File path = new File ("C:\\Área Restrita");
File lista[] = path.listFiles();
public void processa () throws IOException {
String titulo, subtitulo, nomeArq, aux;
for (File s : this.lista) {
aux = s.getName();
//String work
titulo = aux.substring (0, aux.indexOf ("-"));
aux = aux.substring (aux.indexOf ("-")+1);
subtitulo = aux.substring (0, aux.indexOf ("-"));
aux = aux.substring (aux.indexOf ("-")+1);
nomeArq = aux.substring (0);
//Create new file to be copied
final File dest = new File (path + "\\" + nomeArq);
//Copy File
FileCopier copiador = new FileCopier();
copiador.copiaArquivo(s, dest);
//Send file via FTP
FTPUploader ftp = new FTPUploader("**********", "********", "*********", titulo, subtitulo, dest);
ftp.execute();
}
}
public static void main(String[] args) throws IOException {
RestrictedAreaManager ram = new RestrictedAreaManager();
ram.processa();
}
}
FTPUploader 类:
package restrictedareamanager;
import java.awt.HeadlessException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
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 ();
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);
ftp.storeFile (dest.getName(), new FileInputStream (dest.getPath().toString()));
System.out.println ("Done");
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);
}
return null;
}
}