以下是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;
}