最近需要往服务器上传文件就用到ftp上传,我写了个小工具类与大家分享一下。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.asiainfo.wechatservice.service.FtpService;
public class FtpServerImpl {
/**
* Description: 向FTP服务器上传文件
* @param remotePath FTP服务器保存目录
* @param localFile 上传到FTP服务器上的文件名
* @param prot 上传到FTP服务器端口
* @param user FTP服务器用户
* @param password FTP服务器密码
* @param localFile 上传文件
*/
public void upload(String url, int port, String user, String password,String remotePath, String localFile) {
// TODO Auto-generated method stub
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
int reply;
try {
ftpClient.connect(url, port);
ftpClient.login(user, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("faile");
}
File srcFile = new File(localFile);
fis = new FileInputStream(srcFile);
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("utf-8");
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(localFile, fis);
System.out.println("连接成功");
} catch (SocketException e) {
// TODO Auto-generated catch block
throw new RuntimeException("FTP客户端出错!", e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
/**
* Description: 从FTP服务器下载文件
* @param remotePath FTP服务器上的相对路径
* @param remoteFile 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @param prot 上传到FTP服务器端口
* @param user FTP服务器用户
* @param password FTP服务器密码
*/
public void download(String url, int port, String user, String password,String remotePath, String remoteFile, String localPath) {
// TODO Auto-generated method stub
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
int reply;
try {
ftpClient.connect(url, port);
ftpClient.login(user, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("faile");
}
ftpClient.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftpClient.listFiles();
for(FTPFile ff:fs){
if(ff.getName().equals(remoteFile)){
File localFile = new File(localPath+"/"+ff.getName());
fos = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), fos);
fos.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//转移到FTP服务器目录
}