以下是appache commons ftp FTPClient 实例:
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
... ...
/**
* @author rigid
* @param server:FTP服务器的IP地址
* @param user:登录FTP服务器的用户名
* @param password:登录FTP服务器的用户名的口令
* @param path:FTP服务器上的路径
* @param fileName:上传文件名也是ftp服务器上显示的文件名
* @param filePath:本地文件的绝对路径
* @throws Exception
*/
public static boolean ftpFileToMis(String server, String user, String password,String path, String fileName, String filePath) throws Exception {
boolean returnFlag=true;
ftpFileLog.info("上传中......");
FTPClient ftpClient = new FTPClient();
FileInputStream is = null;
int reply;
try {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8"); // GBK
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); // FTPClientConfig.SYST_NT
conf.setServerLanguageCode("zh");
ftpClient.configure(conf);
ftpClient.connect(server);//连接服务器
ftpClient.login(user, password);
reply =ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
ftpFileLog.info( "FTP server refused connection. ");
returnFlag=false;
return false;
}
// path是ftp服务下主目录的子目录
if (path.length() != 0){
if(!ftpClient.changeWorkingDirectory(path)){
if(!ftpClient.makeDirectory(path)){
ftpFileLog.info("创建文件目录【"+path+"】 失败");
returnFlag=false;
return false;
}
}
}
ftpClient.changeWorkingDirectory(path);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
try {
java.io.File file_in = new java.io.File(filePath);
if (file_in.length() == 0) {
System.out.println("file length=0:"+filePath);
ftpFileLog.info("本地文件不存在");
returnFlag=false;
return false;
}else{
is = new FileInputStream(file_in);
returnFlag=ftpClient.storeFile(fileName, is);
ftpFileLog.info("FTP file to service, and the returnFlag = " + returnFlag);
}
ftpClient.logout();
}catch(FileNotFoundException e){
ftpFileLog.info("upload file can not null!");
} finally {
if (is != null) {
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
return returnFlag;
}