首先导入两个jar包:commons-io-1.3.2.jar、commons-net-3.0.1.jar。
示例代码如下:
package com;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
public class FtpTest1 {
public static void main(String[] args) {
//以下是我的FTP服务器的信息
String ip="184.171.16.221";
int port=21;
String userName="foqrume2";
String passWord="qazwasx11`12";
String sourceFileUrl="D:\\数据2011-08-1---2011-08-31.xls";
String ftpGoalDir="/bbs/communitypic";
String downDir="c:\\";
String renameFileName="tang.xls";
String downFileName="downtfq.rar";
testUpload(ip,port,userName,passWord,sourceFileUrl,ftpGoalDir,renameFileName);
//testDownload(ip,port,userName,passWord,ftpGoalDir,downDir,downFileName);
}
/**
* FTP上传单个文件测试
*/
/**
*
*/
/***
* 经测试可以上传文件类型:rar,xls,doc,txt,gif
* @ftpGoalDir:ftp服务器的目录
* @sourceFileUrl 上传文件的路径
*
*/
public static boolean testUpload(String ip,int port,String userName,String passWord,String sourceFileUrl,String ftpGoalDir,String renameFileName) {
//上传不成功
boolean res=false;
//创建一个连接FTP服务器对象
FTPClient ftpClient = new FTPClient();
//创建一个文件写入流对象
FileInputStream fis = null;
try {
//连接FTP服务器
ftpClient.connect(ip);
//登录FTP连接
ftpClient.login(userName, passWord);
//创建文件对象
File srcFile = new File(sourceFileUrl);
//向FTP服务器写入文件
fis = new FileInputStream(srcFile);
//设置上传目录
ftpClient.changeWorkingDirectory(ftpGoalDir);
//向目标服务器写入文件大小限制
ftpClient.setBufferSize(1024);
//
ftpClient.setControlEncoding("GBK");
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(renameFileName, fis);
res=true;
System.out.println("upload successful!");
} 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);
}
}
return res;
}
/**
* FTP下载单个文件测试
*/
public static void testDownload(String ip,int port,String userName,String passWord,String ftpGoalDir,String sourceFileUrl,String renameFileName) {
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
try {
ftpClient.connect(ip);
ftpClient.login(userName, passWord);
String remoteFileName = ftpGoalDir;
fos = new FileOutputStream(sourceFileUrl+"/"+renameFileName);
ftpClient.setBufferSize(1024);
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFileName, fos);
System.out.println("successful!");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fos);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}
上传多个文件示例后续更新中......敬请关注!