利用Apache commons-net 实现;
package com.xwolf.driver.util; import com.xwolf.driver.exception.RunException;
import org.apache.commons.net.ftp.FTPClient; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset; /**
* Created by Administrator on 2015/9/18.
*/
public class FtpUtil {
//用户名
private static final String username ="root";
//密码
private static final String pwd ="root1234";
//主机
private static final String host ="127.0.0.1";
//端口
private static final int port =21;
/*
*上传文件到ftp
* */
public static void upload(FTPClient ftpClient) throws RunException { File file = new File("C:\\Users\\Administrator\\Desktop\\document\\派单OSS报文.xml");
try {
FileInputStream fis = new FileInputStream(file);
//设置FTP文件目录
ftpClient.changeWorkingDirectory("/weblogic/upload");
//缓冲区
ftpClient.setBufferSize(1024);
//字符集 貌似用途不大
ftpClient.setControlEncoding("GBK");
ftpClient.setCharset(Charset.forName("GBK"));
//文件类型(二进制文件)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//保存文件到FTP服务器上 防止中文乱码
ftpClient.storeFile(new String("派单OSS报文_0921.xml".getBytes("GBK"),"iso-8859-1"),fis);
} catch (Exception e) {
throw new RunException("文件上传ftp服务器异常",e);
}
} /**
* 下载文件
* @param ftpClient
*/
public static void download(FTPClient ftpClient) throws RunException {
try {
//保存的文件的名称
FileOutputStream ous = new FileOutputStream(new File("E:\\派单报文.xml"));
ftpClient.setBufferSize(1024);
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//服务器上文件名称
ftpClient.retrieveFile("派单OSS报文_0921.xml",ous);
} catch (Exception e) {
throw new RunException("文件上传ftp服务器异常",e);
}
}
public static void main(String[] args) throws RunException { FTPClient ftpClient=new FTPClient(); try {
//连接FTP
ftpClient.connect(host,port);
//是否登录成功
boolean login = ftpClient.login(username,pwd);
if(login){
download(ftpClient);
} } catch (Exception e) {
throw new RunException("ftp服务器连接异常",e);
} } }