简单的java ftp功能
//仅仅实现了FTP功能。
/**
* @author wuxg
*
*/
package com.wuxg.server.ftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpClient {
private FTPClient ftpClient;
private int reply;
/**
* 连接ftp服务器
*
* @param server 服务器IP
* @param user ftp登陆用户名
* @param password ftp登陆密码
* @throws IOException
*/
public void connectServer(String server,String user,String password)
throws IOException{
ftpClient = new FTPClient();
//连接服务器
ftpClient.connect(server,Constants.PORT);
//登陆
ftpClient.login(user, password);
//上传文件
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
reply=ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
System.out.println("connect error");
}
else{
System.out.println("connect success");
System.out.println("---------------------");
}
}
/**
*
* @param server
* 服务器地址
* @param user
* 登陆用户名
* @param password
* 登陆密码
* @param remotePath
* 远程路径
* @throws IOException
*/
public void connectServer(String server,String user,String password ,String remotePath)
throws IOException {
ftpClient = new FTPClient();
ftpClient.connect(server,Constants.PORT);
ftpClient.login(user, password);
//更换上传目录
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
reply=ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
System.out.println("connect error");
}
else{
System.out.println("connect success");
System.out.println("---------------------");
}
}
/**
* 上传单个文件
*
* @param fileName
* 上传到服务器的文件名
* @param input
* @throws IOException
*/
public void uploadFile(String fileName,InputStream input) throws IOException{
ftpClient.storeFile(fileName,input);
}
/**
* 多个文件目录上传
*
* @param localFile
* 本地上传路径
* @param remotePath
* 上传的ftp服务器上的目录
* @throws IOException
*/
public void uploadMoreFiles(String localFile,String remotePath) throws IOException{
//StringBuffer strBuf =new StringBuffer();
File fi=new File(localFile);
File []fileList=fi.listFiles();
for(File f : fileList){
if(f.isDirectory()){ //如果是目录
String nextPath=f.getName().toString();
//System.out.println("----------"+nextPath);
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.makeDirectory(nextPath);
//ftpClient.changeWorkingDirectory(remotePath+"/"+ nextPath);
String path =(remotePath+"/"+ nextPath).toString();
//System.out.println(path);
uploadMoreFiles(f.getAbsolutePath().toString(),path);
}else{
ftpClient.changeWorkingDirectory(remotePath);
InputStream finput= new FileInputStream(f.getAbsolutePath());
uploadFile(f.getName(),finput);
finput.close();
}
}
}
//关闭ftp
public void closeFtpClient() throws IOException{
if( ftpClient != null){
ftpClient.disconnect();
}
}
}