我所使用的FTP服务器不支持主动连接方式,所以我的程序需要将连接方式设置成为被动。我已经设置成为被动模式了,但是无法上传文件。下面是我的代码,请大虾过目:
连接服务器并设置为被动模式: public void connectServer(String ip, int port, String user, String password, String path, JTextArea textArea) {
try {
ftpClient = new FtpClient();
setConnectTimeOut(5000);
ftpClient.openServer(ip, port);
ftpClient.login(user, password);
// textArea.append(ReadFiles.getDate() + "   登陆成功!\n");
// textArea.setCaretPosition(textArea.getText().length());
System.out.println("登陆成功!");
if (path.length() != 0){
ftpClient.cd(path);
}
ftpClient.binary();
ftpClient.sendServer("PASV");
} catch (IOException ex) {
// textArea.append(ReadFiles.getDate() + "   登陆失败!"+ex+"\n");
// textArea.setCaretPosition(textArea.getText().length());
System.out.println("登陆失败!");
System.out.println(ex);
ex.printStackTrace();
resetFtpClient();
connectServer(ip, port, user, password, path, textArea);
}
}上传文件: public void upload(String path, String localfilename, String remotefilename, JTextArea textArea) {
changeDirs(path, textArea);
this.localfilename = localfilename; // c:/1.txt
this.remotefilename = remotefilename;// 1.txt
System.out.println("UPLOADING...");
textArea.append(ReadFiles.getDate() + "   正在上传       [" + remotefilename + "]...\n");
textArea.setCaretPosition(textArea.getText().length());
try {
TelnetOutputStream out = ftpClient.put(this.remotefilename);
File file_in = new File(this.localfilename);
FileInputStream in = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
}
textArea.append(ReadFiles.getDate() + "   上传文件       [" + remotefilename + "]成功!\n");
textArea.setCaretPosition(textArea.getText().length());
in.close();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("ERROR!");
textArea.append(ex + "\n");
textArea.append(ReadFiles.getDate() + "   上传文件失败!\n");
textArea.setCaretPosition(textArea.getText().length());

resetFtpClient();
connectServer(host, port, username, password, path, textArea);
upload(path, localfilename, remotefilename, textArea);
}
}
以下是异常:sun.net.ftp.FtpProtocolException: REIN:502 REIN not implemented.
将FTP连接设置为被动模式,谢谢!!! void resetFtpClient(){
try {
if(ftpClient.serverIsOpen()){
ftpClient.reInit();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
进入异常后,执行上面这个方法时报错:
ftpClient.reInit();谢谢各位!