首先导入包
import org.apache.commons.NET.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
FTPClient类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立”代理”的各种信息。下面给出了这些实例变量。
public static boolean useFtpProxy
这个变量用于表明FTP传输过程中是否使用了一个代理,因此,它实际上是一个标记,此标记若为TRUE,表明使用了一个代理主机。
public static String ftpProxyHost
此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机名。
public static int ftpProxyPort
此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机的端口地址。
FtpClient有三种不同形式的构造函数,如下所示:
1、public FtpClient(String hostname,int port)
此构造函数利用给出的主机名和端口号建立一条FTP连接。
2、public FtpClient(String hostname)
此构造函数利用给出的主机名建立一条FTP连接,使用默认端口号。
3、FtpClient()
此构造函数将创建一FtpClient类,但不建立FTP连接。这时,FTP连接可以用openServer方法建立。
一旦建立了类FtpClient,就可以用这个类的方法来打开与FTP服务器的连接。类ftpClient提供了如下两个可用于打开与FTP服务器之间的连接的方法。
public void openServer(String hostname)
这个方法用于建立一条与指定主机上的FTP服务器的连接,使用默认端口号。
public void openServer(String host,int port)
这个方法用于建立一条与指定主机、指定端口上的FTP服务器的连接。
打开连接之后,接下来的工作是注册到FTP服务器。这时需要利用下面的方法。
public void login(String username,String password)
此方法利用参数username和password登录到FTP服务器。使用过Intemet的用户应该知道,匿名FTP服务器的登录用户名为anonymous,密码一般用自己的电子邮件地址。
下面是FtpClient类所提供的一些控制命令。
public void cd(String remoteDirectory)
该命令用于把远程系统上的目录切换到参数remoteDirectory所指定的目录。
public void cdUp():该命令用于把远程系统上的目录切换到上一级目录。
public String pwd():该命令可显示远程系统上的目录状态。
public void binary():该命令可把传输格式设置为二进制格式。
public void ascii():该命令可把传输协议设置为ASCII码格式。
public void rename(String string,String string1)
该命令可对远程系统上的目录或者文件进行重命名操作。
除了上述方法外,类FtpClient还提供了可用于传递并检索目录清单和文件的若干方法。这些方法返回的是可供读或写的输入、输出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回与远程机器上当前目录相对应的输入流。
public TelnetInputStream get(String filename)
获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
public TelnetOutputStream put(String filename)
以写方式打开一输出流,通过这一输出流把文件filename传送到远程计算机。
案例:
public FTPClient ftp = new FTPClient(); // 实例化ftp客户端对象。
/*******************登陆***********************/
// 开始读取 就去连接FTP服务器
if (ftp.isConnected() == false)
{
try
{
ftp.connect(host_ip);// 连接 Ftp host_ip FTP服务器ip
try
{
ftp.login(username, password);// 登陆 login ()方法登陆ftp
ftp.setFileType(FTPClient.ASCII_FILE_TYPE);// 设置文件类型setFileType()设置ftp文件类型
} catch (Exception e1)
{
log.error(“faile to load!!!!”);
}
} catch (SocketException e1)
{
log.error(“建立连接FTP连接失败”);
} catch (IOException e1)
{
log.error(“IO异常FTP.txt读取失败”);
}
}
/**************下载文件***************************/
public void downloadFiles()
{
// 进入FTP服务器工作目录
ftp.changeWorkingDirectory(ftp.printWorkingDirectory()+ remote_dir); // remote_dir FTP远程文件目录
// 获得远程ftp目录下的文件列表
FTPFile[] fileList = ftp.listFiles(“.”); // . 号可替换成文件指定ftp目录。获取FTPfile文件列表。注意:文件列表包含文件夹及文件
String[] files = ftp.listNames(); // 获取FTP服务器文件名称列表。注意:文件列表包含文件夹及文件的名称。
/*
fileList[0].getGroup(); // 文件所属组 ,对应有set
fileList[0].getName(); // 文件名称, setName(“”)重命名
fileList[0].getSize(); // 文件大小 返回long数据类型
fileList[0].getTimestamp().getTime(); //文件最后修改时间
fileList[0].getType(); //文件类型
fileList[0].getUser(); //文件所属用户
fileList[0].isDirectory(); // 文件是不是文件夹
fileList[0].isFile(); //判断是不是 文件
fileList[0].isSymbolicLink(); // ???
fileList[0].isUnknown(); // ?、、
fileList[0].DIRECTORY_TYPE; //属性,文件夹类型 返回int型
fileList[0].FILE_TYPE; // 属性, 文件类型, 返回int型
fileList[0].GROUP_ACCESS; //组, 返回int型
*/
//下载指定文件的时候,要判断指定文件的名称,比如下载,AA.TXT文件
//遍历获取的FTP文件名称列表
for(int i ; i < fileList.length (标注: 或者files.length ); i ++ )
{
//判断文件名是否包含AA.txt的。注意:在 Linux里 fileList 对象获取不到length属性。必须通过files属性获取。判断文件名称列表也必须从files数组中获取。
if(fileList[i].getName().indexOf(“AA.txt”) != -1)
{
File localfile = new File(local_dir+”/”+fileList[i].getName());
OutPutStream ops = FileOutputStream(localFile);
ftp.retrieveFile(fileList[i].getName(), ops); //将FTP上指定文件名称的文件,下载到本地指定输出流的文件夹中。
ops.close();
}
}
}
/******************上传指定文件***********************/
/**
* Description: 向FTP服务器上传文件
* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
@Test
public void testUpLoadFromDisk(){
try {
FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
案例一:
用apache FTP client实现FTP客户端–支持断点续传和中文文件
利用org.apache.commons.Net.ftp包实现一个简单的ftp客户端实用类。主要实现一下功能
1.支持上传下载。支持断点续传
2.支持进度汇报
3.支持对于中文目录及中文文件创建的支持。
枚举类UploadStatus代码
- 1. public enum UploadStatus {
- 2. Create_Directory_Fail, //远程服务器相应目录创建失败
- 3. Create_Directory_Success, //远程服务器闯将目录成功
- 4. Upload_New_File_Success, //上传新文件成功
- 5. Upload_New_File_Failed, //上传新文件失败
- 6. File_Exits, //文件已经存在
- 7. Remote_Bigger_Local, //远程文件大于本地文件
- 8. Upload_From_Break_Success, //断点续传成功
- 9. Upload_From_Break_Failed, //断点续传失败
- 10. Delete_Remote_Faild; //删除远程文件失败
- 11. }
枚举类DownloadStatus代码
- 1. public enum DownloadStatus {
- 2. Remote_File_Noexist, //远程文件不存在
- 3. Local_Bigger_Remote, //本地文件大于远程文件
- 4. Download_From_Break_Success, //断点下载文件成功
- 5. Download_From_Break_Failed, //断点下载文件失败
- 6. Download_New_Success, //全新下载文件成功
- 7. Download_New_Failed; //全新下载文件失败
- 8. }
核心FTP代码
- 核心FTP代码
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.io.RandomAccessFile;
- import open.mis.data.DownloadStatus;
- import open.mis.data.UploadStatus;
- import org.apache.commons.net.PrintCommandListener;
- import org.apache.commons.net.ftp.FTP;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
- /**
- * 支持断点续传的FTP实用类
- * @author BenZhou
- * @version 0.1 实现基本断点上传下载
- * @version 0.2 实现上传下载进度汇报
- * @version 0.3 实现中文目录创建及中文文件创建,添加对于中文的支持
- */
- public class ContinueFTP {
- public FTPClient ftpClient = new FTPClient();
- public ContinueFTP(){
- //设置将过程中使用到的命令输出到控制台
- this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
- }
- /**
- * 连接到FTP服务器
- * @param hostname 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 是否连接成功
- * @throws IOException
- */
- public boolean connect(String hostname,int port,String username,String password) throws IOException{
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(”GBK”);
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- return true;
- }
- }
- disconnect();
- return false;
- }
- /**
- * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报
- * @param remote 远程文件路径
- * @param local 本地文件路径
- * @return 上传的状态
- * @throws IOException
- */
- public DownloadStatus download(String remote,String local) throws IOException{
- //设置被动模式
- ftpClient.enterLocalPassiveMode();
- //设置以二进制方式传输
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- DownloadStatus result;
- //检查远程文件是否存在
- FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- if(files.length != 1){
- System.out.println(“远程文件不存在”);
- return DownloadStatus.Remote_File_Noexist;
- }
- long lRemoteSize = files[0].getSize();
- File f = new File(local);
- //本地存在文件,进行断点下载
- if(f.exists()){
- long localSize = f.length();
- //判断本地文件大小是否大于远程文件大小
- if(localSize >= lRemoteSize){
- System.out.println(“本地文件大于远程文件,下载中止”);
- return DownloadStatus.Local_Bigger_Remote;
- }
- //进行断点续传,并记录状态
- FileOutputStream out = new FileOutputStream(f,true);
- ftpClient.setRestartOffset(localSize);
- InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- byte[] bytes = new byte[1024];
- long step = lRemoteSize /100;
- long process=localSize /step;
- int c;
- while((c = in.read(bytes))!= -1){
- out.write(bytes,0,c);
- localSize+=c;
- long nowProcess = localSize /step;
- if(nowProcess > process){
- process = nowProcess;
- if(process % 10 == 0)
- System.out.println(“下载进度:”+process);
- //TODO 更新文件下载进度,值存放在process变量中
- }
- }
- in.close();
- out.close();
- boolean isDo = ftpClient.completePendingCommand();
- if(isDo){
- result = DownloadStatus.Download_From_Break_Success;
- }else {
- result = DownloadStatus.Download_From_Break_Failed;
- }
- }else {
- OutputStream out = new FileOutputStream(f);
- InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));
- byte[] bytes = new byte[1024];
- long step = lRemoteSize /100;
- long process=0;
- long localSize = 0L;
- int c;
- while((c = in.read(bytes))!= -1){
- out.write(bytes, 0, c);
- localSize+=c;
- long nowProcess = localSize /step;
- if(nowProcess > process){
- process = nowProcess;
- if(process % 10 == 0)
- System.out.println(“下载进度:”+process);
- //TODO 更新文件下载进度,值存放在process变量中
- }
- }
- in.close();
- out.close();
- boolean upNewStatus = ftpClient.completePendingCommand();
- if(upNewStatus){
- result = DownloadStatus.Download_New_Success;
- }else {
- result = DownloadStatus.Download_New_Failed;
- }
- }
- return result;
- }
- /**
- * 上传文件到FTP服务器,支持断点续传
- * @param local 本地文件名称,绝对路径
- * @param remote 远程文件路径,使用/home/directory1/subdirectory/file.ext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
- * @return 上传结果
- * @throws IOException
- */
- public UploadStatus upload(String local,String remote) throws IOException{
- //设置PassiveMode传输
- ftpClient.enterLocalPassiveMode();
- //设置以二进制流的方式传输
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.setControlEncoding(”GBK”);
- UploadStatus result;
- //对远程目录的处理
- String remoteFileName = remote;
- if(remote.contains(“/”)){
- remoteFileName = remote.substring(remote.lastIndexOf(”/”)+1);
- //创建服务器远程目录结构,创建失败直接返回
- if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){
- return UploadStatus.Create_Directory_Fail;
- }
- }
- //检查远程是否存在文件
- FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes(“GBK”),“iso-8859-1”));
- if(files.length == 1){
- long remoteSize = files[0].getSize();
- File f = new File(local);
- long localSize = f.length();
- if(remoteSize==localSize){
- return UploadStatus.File_Exits;
- }else if(remoteSize > localSize){
- return UploadStatus.Remote_Bigger_Local;
- }
- //尝试移动文件内读取指针,实现断点续传
- result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
- //如果断点续传没有成功,则删除服务器上文件,重新上传
- if(result == UploadStatus.Upload_From_Break_Failed){
- if(!ftpClient.deleteFile(remoteFileName)){
- return UploadStatus.Delete_Remote_Faild;
- }
- result = uploadFile(remoteFileName, f, ftpClient, 0);
- }
- }else {
- result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
- }
- return result;
- }
- /**
- * 断开与远程服务器的连接
- * @throws IOException
- */
- public void disconnect() throws IOException{
- if(ftpClient.isConnected()){
- ftpClient.disconnect();
- }
- }
- /**
- * 递归创建远程服务器目录
- * @param remote 远程服务器文件绝对路径
- * @param ftpClient FTPClient对象
- * @return 目录创建是否成功
- * @throws IOException
- */
- public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{
- UploadStatus status = UploadStatus.Create_Directory_Success;
- String directory = remote.substring(0,remote.lastIndexOf(”/”)+1);
- if(!directory.equalsIgnoreCase(“/”)&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes(“GBK”),“iso-8859-1”))){
- //如果远程目录不存在,则递归创建远程服务器目录
- int start=0;
- int end = 0;
- if(directory.startsWith(“/”)){
- start = 1;
- }else{
- start = 0;
- }
- end = directory.indexOf(”/”,start);
- while(true){
- String subDirectory = new String(remote.substring(start,end).getBytes(“GBK”),“iso-8859-1”);
- if(!ftpClient.changeWorkingDirectory(subDirectory)){
- if(ftpClient.makeDirectory(subDirectory)){
- ftpClient.changeWorkingDirectory(subDirectory);
- }else {
- System.out.println(“创建目录失败”);
- return UploadStatus.Create_Directory_Fail;
- }
- }
- start = end + 1;
- end = directory.indexOf(”/”,start);
- //检查所有目录是否创建完毕
- if(end <= start){
- break;
- }
- }
- }
- return status;
- }
- /**
- * 上传文件到服务器,新上传和断点续传
- * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变
- * @param localFile 本地文件File句柄,绝对路径
- * @param processStep 需要显示的处理进度步进值
- * @param ftpClient FTPClient引用
- * @return
- * @throws IOException
- */
- public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{
- UploadStatus status;
- //显示进度的上传
- long step = localFile.length() / 100;
- long process = 0;
- long localreadbytes = 0L;
- RandomAccessFile raf = new RandomAccessFile(localFile,“r”);
- OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(“GBK”),“iso-8859-1”));
- //断点续传
- if(remoteSize>0){
- ftpClient.setRestartOffset(remoteSize);
- process = remoteSize /step;
- raf.seek(remoteSize);
- localreadbytes = remoteSize;
- }
- byte[] bytes = new byte[1024];
- int c;
- while((c = raf.read(bytes))!= -1){
- out.write(bytes,0,c);
- localreadbytes+=c;
- if(localreadbytes / step != process){
- process = localreadbytes / step;
- System.out.println(“上传进度:” + process);
- //TODO 汇报上传状态
- }
- }
- out.flush();
- raf.close();
- out.close();
- boolean result =ftpClient.completePendingCommand();
- if(remoteSize > 0){
- status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
- }else {
- status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
- }
- return status;
- }
- public static void main(String[] args) {
- ContinueFTP myFtp = new ContinueFTP();
- try {
- myFtp.connect(”192.168.21.181”, 21, “nid”, “123”);
- // myFtp.ftpClient.makeDirectory(new String(“电视剧”.getBytes(“GBK”),”iso-8859-1”));
- // myFtp.ftpClient.changeWorkingDirectory(new String(“电视剧”.getBytes(“GBK”),”iso-8859-1”));
- // myFtp.ftpClient.makeDirectory(new String(“走西口”.getBytes(“GBK”),”iso-8859-1”));
- // System.out.println(myFtp.upload(“E://yw.flv”, ”/yw.flv”,5));
- // System.out.println(myFtp.upload(“E://走西口24.mp4”,”/央视走西口/新浪网/走西口24.mp4”));
- System.out.println(myFtp.download(“/央视走西口/新浪网/走西口24.mp4”, “E://走西口242.mp4”));
- myFtp.disconnect();
- } catch (IOException e) {
- System.out.println(“连接FTP出错:”+e.getMessage());
- }
- }
- }
案例二:
FTP客户端
package cm;
import Java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FtpHelper {
private FTPClient ftpClient = new FTPClient();
/**
* 连接到FTP服务器
*
* @param hostname
* 主机名
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return 是否连接成功
* @throws IOException
*/
public boolean connect(String hostname, int port, String username,
String password) throws IOException {
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(“GBK”);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(username, password)) {
return true;
}
}
disconnect();
return false;
}
/**
* 从FTP服务器上下载文件,支持断点续传,上传百分比汇报
*
* @param remote
* 远程文件路径
* @param local
* 本地文件路径
* @return 上传的状态
* @throws IOException
*/
public DownloadStatus download(String remote, String local)
throws IOException {
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatus result;
// 检查远程文件是否存在
FTPFile[] files = ftpClient.listFiles(new String(
remote.getBytes(“GBK”), “iso-8859-1”));
if (files.length != 1) {
System.out.println(“远程文件不存在”);
return DownloadStatus.Remote_File_Noexist;
}
long lRemoteSize = files[0].getSize();
File f = new File(local);
// 本地存在文件,进行断点下载
if (f.exists()) {
long localSize = f.length();
// 判断本地文件大小是否大于远程文件大小
if (localSize >= lRemoteSize) {
System.out.println(“本地文件大于远程文件,下载中止”);
return DownloadStatus.Local_Bigger_Remote;
}
// 进行断点续传,并记录状态
FileOutputStream out = new FileOutputStream(f, true);
ftpClient.setRestartOffset(localSize);
InputStream in = ftpClient.retrieveFileStream(new String(remote
.getBytes(“GBK”), “iso-8859-1”));
byte[] bytes = new byte[1024];
long step = lRemoteSize / 100;
long process = localSize / step;
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
localSize += c;
long nowProcess = localSize / step;
if (nowProcess > process) {
process = nowProcess;
if (process % 10 == 0)
System.out.println(“下载进度:” + process);
// TODO 更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
boolean isDo = ftpClient.completePendingCommand();
if (isDo) {
result = DownloadStatus.Download_From_Break_Success;
} else {
result = DownloadStatus.Download_From_Break_Failed;
}
} else {
OutputStream out = new FileOutputStream(f);
InputStream in = ftpClient.retrieveFileStream(new String(remote
.getBytes(“GBK”), “iso-8859-1”));
byte[] bytes = new byte[1024];
long step = lRemoteSize / 100;
long process = 0;
long localSize = 0L;
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
localSize += c;
long nowProcess = localSize / step;
if (nowProcess > process) {
process = nowProcess;
if (process % 10 == 0)
System.out.println(“下载进度:” + process);
// TODO 更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if (upNewStatus) {
result = DownloadStatus.Download_New_Success;
} else {
result = DownloadStatus.Download_New_Failed;
}
}
return result;
}
/**
* 上传文件到FTP服务器,支持断点续传
*
* @param local
* 本地文件名称,绝对路径
* @param remote
* 远程文件路径,使用/home/directory1/subdirectory/file.ext
* 按照linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
* @return 上传结果
* @throws IOException
*/
public UploadStatus upload(String local, String remote) throws IOException {
// 设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
// 设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding(“GBK”);
UploadStatus result;
// 对远程目录的处理
String remoteFileName = remote;
if (remote.contains(“/”)) {
remoteFileName = remote.substring(remote.lastIndexOf(“/”) + 1);
// 创建服务器远程目录结构,创建失败直接返回
if (createDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
return UploadStatus.Create_Directory_Fail;
}
}
//ftpClient.feat();
// System.out.println( ftpClient.getReply());
// System.out.println( ftpClient.acct(null));
// System.out.println(ftpClient.getReplyCode());
// System.out.println(ftpClient.getReplyString());
// 检查远程是否存在文件
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
.getBytes(“GBK”), “iso-8859-1”));
if (files.length == 1) {
long remoteSize = files[0].getSize();
File f = new File(local);
long localSize = f.length();
if (remoteSize == localSize) { // 文件存在
return UploadStatus.File_Exits;
} else if (remoteSize > localSize) {
return UploadStatus.Remote_Bigger_Local;
}
// 尝试移动文件内读取指针,实现断点续传
result = uploadFile(remoteFileName, f, ftpClient, remoteSize);
// 如果断点续传没有成功,则删除服务器上文件,重新上传
if (result == UploadStatus.Upload_From_Break_Failed) {
if (!ftpClient.deleteFile(remoteFileName)) {
return UploadStatus.Delete_Remote_Faild;
}
result = uploadFile(remoteFileName, f, ftpClient, 0);
}
} else {
result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
}
return result;
}
/**
* 断开与远程服务器的连接
*
* @throws IOException
*/
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
/**
* 递归创建远程服务器目录
*
* @param remote
* 远程服务器文件绝对路径
* @param ftpClient
* FTPClient对象
* @return 目录创建是否成功
* @throws IOException
*/
public UploadStatus createDirecroty(String remote, FTPClient ftpClient)
throws IOException {
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0, remote.lastIndexOf(“/”) + 1);
if (!directory.equalsIgnoreCase(“/”)
&& !ftpClient.changeWorkingDirectory(new String(directory
.getBytes(“GBK”), “iso-8859-1”))) {
// 如果远程目录不存在,则递归创建远程服务器目录
int start = 0;
int end = 0;
if (directory.startsWith(“/”)) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf(“/”, start);
while (true) {
String subDirectory = new String(remote.substring(start, end)
.getBytes(“GBK”), “iso-8859-1”);
if (!ftpClient.changeWorkingDirectory(subDirectory)) {
if (ftpClient.makeDirectory(subDirectory)) {
ftpClient.changeWorkingDirectory(subDirectory);
} else {
System.out.println(“创建目录失败”);
return UploadStatus.Create_Directory_Fail;
}
}
start = end + 1;
end = directory.indexOf(“/”, start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return status;
}
/**
* 上传文件到服务器,新上传和断点续传
*
* @param remoteFile
* 远程文件名,在上传之前已经将服务器工作目录做了改变
* @param localFile
* 本地文件File句柄,绝对路径
* @param processStep
* 需要显示的处理进度步进值
* @param ftpClient
* FTPClient引用
* @return
* @throws IOException
*/
public UploadStatus uploadFile(String remoteFile, File localFile,
FTPClient ftpClient, long remoteSize) throws IOException {
UploadStatus status;
// 显示进度的上传
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile, “r”);
String remote = new String(remoteFile.getBytes(“GBK”), “iso-8859-1”);
OutputStream out = ftpClient.appendFileStream(remote);
if(out==null)
{
String message = ftpClient.getReplyString();
throw new RuntimeException(message);
}
// 断点续传
if (remoteSize > 0) {
ftpClient.setRestartOffset(remoteSize);
process = remoteSize / step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while ((c = raf.read(bytes)) != -1) {
out.write(bytes, 0, c);
localreadbytes += c;
if (localreadbytes / step != process) {
process = localreadbytes / step;
System.out.println(“上传进度:” + process);
// TODO 汇报上传状态
}
}
out.flush();
raf.close();
out.close();
boolean result = ftpClient.completePendingCommand();
if (remoteSize > 0) {
status = result ? UploadStatus.Upload_From_Break_Success
: UploadStatus.Upload_From_Break_Failed;
} else {
status = result ? UploadStatus.Upload_New_File_Success
: UploadStatus.Upload_New_File_Failed;
}
return status;
}
/**
* 获取指定目录下的文件名称列表
* @author HQQW510_64
* @param currentDir 需要获取其子目录的当前目录名称
* @return 返回子目录字符串数组
*/
public String[] GetFileNames(String currentDir) {
String[] dirs = null;
try {
if(currentDir==null)
dirs = ftpClient.listNames();
else
dirs = ftpClient.listNames(currentDir);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dirs;
}
/**
* 获取指定目录下的文件与目录信息集合
* @param currentDir 指定的当前目录
* @return 返回的文件集合
*/
public FTPFile[] GetDirAndFilesInfo(String currentDir)
{
FTPFile[] files=null;
try
{
if(currentDir==null)
files=ftpClient.listFiles();
else
files = ftpClient.listFiles(currentDir);
}
catch(IOException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
return files;
}
}
案例三
JAVA中使用FTPClient上传下载
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。
一、上传文件
原理就不介绍了,大家直接看代码吧
- /**
- * Description: 向FTP服务器上传文件
- * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建
- * @param url FTP服务器hostname
- * @param port FTP服务器端口
- * @param username FTP登录账号
- * @param password FTP登录密码
- * @param path FTP服务器保存目录
- * @param filename 上传到FTP服务器上的文件名
- * @param input 输入流
- * @return 成功返回true,否则返回false
- */
- public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);//连接FTP服务器
- //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftp.login(username, password);//登录
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(path);
- ftp.storeFile(filename, input);
- input.close();
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }<pre></pre>
下面我们写两个小例子:
1.将本地文件上传到FTP服务器上,代码如下:
- @Test
- public void testUpLoadFromDisk(){
- try {
- FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
- boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
- System.out.println(flag);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }<pre></pre>
2.在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
- @Test
- public void testUpLoadFromString(){
- try {
- InputStream input = new ByteArrayInputStream(“test ftp”.getBytes(“utf-8”));
- boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, input);
- System.out.println(flag);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }<pre></pre>
二、下载文件
从FTP服务器下载文件的代码也很简单,参考如下:
- /**
- * Description: 从FTP服务器下载文件
- * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保(cuihongbao@d-heaven.com)创建
- * @param url FTP服务器hostname
- * @param port FTP服务器端口
- * @param username FTP登录账号
- * @param password FTP登录密码
- * @param remotePath FTP服务器上的相对路径
- * @param fileName 要下载的文件名
- * @param localPath 下载后保存到本地的路径
- * @return
- */
- public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);
- //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftp.login(username, password);//登录
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
- FTPFile[] fs = ftp.listFiles();
- for(FTPFile ff:fs){
- if(ff.getName().equals(fileName)){
- File localFile = new File(localPath+“/”+ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftp.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }<pre></pre>
案例三:
- /**
- * 支持断点续传的FTP实用类
- *
- * @author chenxin
- * @version [版本号, 2012-5-21]
- * @see [相关类/方法]
- * @since [产品/模块版本]
- */
- public class FtpUtils {
- private FTPClient ftpClient = null;
- private static final Logger logger = Logger.getLogger(FtpUtils.class);
- private String hostname;
- private String username;
- private String password;
- private int port;
- private static final String EPUB_DIR = “epub_file”;
- public FtpUtils()
- {
- ftpClient = new FTPClient();
- username = ServerConfig.get(”ftp/ftp-user”, “”);
- password = ServerConfig.get(”ftp/ftp-password”, “”);
- hostname = ServerConfig.get(”ftp/ftp-host”, “”);
- port = ServerConfig.getInt(”ftp/ftp-port”, 21);
- // {
- // //设置将过程中使用到的命令输出到控制台
- // ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
- // }
- }
- /**
- * 连接到FTP服务器
- * @param hostname 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 是否连接成功
- * @throws IOException
- */
- public boolean connect() throws IOException{
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”, “GBK”));
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- // 设置被动模式
- ftpClient.enterLocalPassiveMode();
- // 设置以二进制方式传输
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- return true;
- }
- }
- disconnect();
- return false;
- }
- public boolean reconnect() throws IOException
- {
- disconnect();
- ftpClient.connect(hostname, port);
- ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”, “GBK”));
- if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
- if(ftpClient.login(username, password)){
- // 设置被动模式
- ftpClient.enterLocalPassiveMode();
- // 设置以二进制方式传输
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- return true;
- }
- }
- disconnect();
- return false;
- }
- /**
- * 从FTP服务器上下载文件,上传百分比
- * @param remote
- * @param dir
- * @param fileName
- * @return
- * @throws IOException
- * @see [类、类#方法、类#成员]
- */
- public boolean download(String remote, String dir, String fileName)
- throws IOException
- {
- File file = new File(dir + File.separator + fileName);
- // 本地存在文件
- if (file.exists())
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File is existsed.”);
- }
- // 如果文件存在,但还未从FTP服务器上完全取下来,则需要等待
- Long initialSize = 0L;
- int i = 0;
- while (initialSize != file.length())
- {
- i++;
- initialSize = file.length();
- try
- {
- Thread.sleep(100L);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- if (i > 1)
- {
- // 如果是刚下完的文件,则不需要再比对大小是否一致
- return true;
- }
- }
- Long localSize = file.length();
- File localDir = new File(dir);
- if (!localDir.exists())
- {
- localDir.mkdirs();
- }
- // 检查远程文件是否存在
- if (remote.startsWith(“/”))
- {
- remote = remote.substring(1);
- }
- if (ftpClient.listNames(remote).length <= 0)
- {
- // 文件不存在
- logger.error(”Could not find file from ftp server: ” + remote);
- return false;
- }
- // 计算远程文件大小
- String s = ”SIZE ” + remote + “\r\n”;
- ftpClient.sendCommand(s);
- String s1 = ftpClient.getReplyString();
- Long remoteSize = Long.parseLong(s1.substring(3).trim());
- if (logger.isDebugEnabled())
- {
- logger.debug(”localsize: ” + localSize + “, remoteSize: ” + remoteSize);
- }
- if (remoteSize.equals(localSize))
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File’s size not changed.”);
- }
- return true;
- }
- else if (localSize != 0L)
- {
- if (logger.isDebugEnabled())
- {
- logger.debug(”File’s size changed which needed re-download.”);
- }
- //远程文件和本地文件大小不一致,则删除本地文件
- file.delete();
- //如果是EPUB书路径,则需要把解压过的临时文件也一并删除
- if (dir.indexOf(EPUB_DIR) > 0)
- {
- deleteAll(localDir);
- }
- }
- // 重连以回到根目录
- reconnect();
- OutputStream out = new FileOutputStream(file);
- InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“UTF-8”),
- ServerConfig.get(”ftp/ftp-charset”, “GBK”)));
- if (logger.isDebugEnabled())
- {
- logger.debug(”Begin to downloaded file from ftp.”);
- }
- byte[] bytes = new byte[1024];
- int count;
- while ((count = in.read(bytes)) != -1)
- {
- out.write(bytes, 0, count);
- }
- if (logger.isDebugEnabled())
- {
- logger.debug(”File has been downloaded from ftp successfully.”);
- }
- in.close();
- out.close();
- boolean upNewStatus = ftpClient.completePendingCommand();
- if (upNewStatus)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //递归删除文件夹
- private void deleteAll(File file)
- {
- if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
- {
- for (File childFile : file.listFiles())
- {
- deleteAll(childFile);
- }
- }
- else
- {
- file.delete();
- }
- }
- /** *//**
- * 断开与远程服务器的连接
- * @throws IOException
- */
- public void disconnect() throws IOException{
- if(ftpClient.isConnected()){
- ftpClient.disconnect();
- }
- }
- public static void main(String[] args) {
- FtpUtils myFtp = new FtpUtils();
- try {
- myFtp.connect();
- System.out.println(myFtp.download(”/央视走西口/新浪网/走西口24.mp4”, “E:\\走西口242.mp4”, “123”));
- myFtp.disconnect();
- } catch (IOException e) {
- System.out.println(”连接FTP出错:”+e.getMessage());
- }
- }
- //使用: 下载文件
- FtpUtils ftpUtils = new FtpUtils();
- ftpUtils.connect();
- ftpUtils.download(fileUrl, directoryPath, filename);
- ftpUtils.disconnect();
- }
/**
* 支持断点续传的FTP实用类
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class FtpUtils {
private FTPClient ftpClient = null;
private static final Logger logger = Logger.getLogger(FtpUtils.class);
private String hostname;
private String username;
private String password;
private int port;
private static final String EPUB_DIR = "epub_file";
public FtpUtils()
{
ftpClient = new FTPClient();
username = ServerConfig.get("ftp/ftp-user", "");
password = ServerConfig.get("ftp/ftp-password", "");
hostname = ServerConfig.get("ftp/ftp-host", "");
port = ServerConfig.getInt("ftp/ftp-port", 21);
// {
// //设置将过程中使用到的命令输出到控制台
// ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
// }
}
/**
* 连接到FTP服务器
* @param hostname 主机名
* @param port 端口
* @param username 用户名
* @param password 密码
* @return 是否连接成功
* @throws IOException
*/
public boolean connect() throws IOException{
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
public boolean reconnect() throws IOException
{
disconnect();
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username, password)){
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return true;
}
}
disconnect();
return false;
}
/**
* 从FTP服务器上下载文件,上传百分比
* @param remote
* @param dir
* @param fileName
* @return
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public boolean download(String remote, String dir, String fileName)
throws IOException
{
File file = new File(dir + File.separator + fileName);
// 本地存在文件
if (file.exists())
{
if (logger.isDebugEnabled())
{
logger.debug("File is existsed.");
}
// 如果文件存在,但还未从FTP服务器上完全取下来,则需要等待
Long initialSize = 0L;
int i = 0;
while (initialSize != file.length())
{
i++;
initialSize = file.length();
try
{
Thread.sleep(100L);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (i > 1)
{
// 如果是刚下完的文件,则不需要再比对大小是否一致
return true;
}
}
Long localSize = file.length();
File localDir = new File(dir);
if (!localDir.exists())
{
localDir.mkdirs();
}
// 检查远程文件是否存在
if (remote.startsWith("/"))
{
remote = remote.substring(1);
}
if (ftpClient.listNames(remote).length <= 0)
{
// 文件不存在
logger.error("Could not find file from ftp server: " + remote);
return false;
}
// 计算远程文件大小
String s = "SIZE " + remote + "\r\n";
ftpClient.sendCommand(s);
String s1 = ftpClient.getReplyString();
Long remoteSize = Long.parseLong(s1.substring(3).trim());
if (logger.isDebugEnabled())
{
logger.debug("localsize: " + localSize + ", remoteSize: " + remoteSize);
}
if (remoteSize.equals(localSize))
{
if (logger.isDebugEnabled())
{
logger.debug("File's size not changed.");
}
return true;
}
else if (localSize != 0L)
{
if (logger.isDebugEnabled())
{
logger.debug("File's size changed which needed re-download.");
}
//远程文件和本地文件大小不一致,则删除本地文件
file.delete();
//如果是EPUB书路径,则需要把解压过的临时文件也一并删除
if (dir.indexOf(EPUB_DIR) > 0)
{
deleteAll(localDir);
}
}
// 重连以回到根目录
reconnect();
OutputStream out = new FileOutputStream(file);
InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8"),
ServerConfig.get("ftp/ftp-charset", "GBK")));
if (logger.isDebugEnabled())
{
logger.debug("Begin to downloaded file from ftp.");
}
byte[] bytes = new byte[1024];
int count;
while ((count = in.read(bytes)) != -1)
{
out.write(bytes, 0, count);
}
if (logger.isDebugEnabled())
{
logger.debug("File has been downloaded from ftp successfully.");
}
in.close();
out.close();
boolean upNewStatus = ftpClient.completePendingCommand();
if (upNewStatus)
{
return true;
}
else
{
return false;
}
}
//递归删除文件夹
private void deleteAll(File file)
{
if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
{
for (File childFile : file.listFiles())
{
deleteAll(childFile);
}
}
else
{
file.delete();
}
}
/** *//**
* 断开与远程服务器的连接
* @throws IOException
*/
public void disconnect() throws IOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
public static void main(String[] args) {
FtpUtils myFtp = new FtpUtils();
try {
myFtp.connect();
System.out.println(myFtp.download("/央视走西口/新浪网/走西口24.mp4", "E:\\走西口242.mp4", "123"));
myFtp.disconnect();
} catch (IOException e) {
System.out.println("连接FTP出错:"+e.getMessage());
}
}
//使用: 下载文件
FtpUtils ftpUtils = new FtpUtils();
ftpUtils.connect();
ftpUtils.download(fileUrl, directoryPath, filename);
ftpUtils.disconnect();
}
案例四
sun.net.ftp.FtpClient.,该类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立”代理”的各种信息。下面给出了这些实例变量。
直接给大家上代码,想要用功能的直接拿过来用接可以:
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.sql.Connection;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Vector;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
- public class TfpTools {
- //连接ftp
- private FTPClient ftpClient = null;
- // public static String ip = “117.21.208.37”;
- // public static int port = 21;
- // public static String username = “eftp”;
- // public static String password = “e1f2t3p4”;
- // public static String sub_path = ”/opt/tomcat/webapps/photocdn/msgdata/”;
- /**
- * 连接ftp
- */
- public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
- int i = 10;
- if (ftpClient == null) {
- int reply;
- while (i > 0) {
- try {
- ftpClient = new FTPClient();
- if (port != 21)
- ftpClient.connect(ip, port);
- else
- ftpClient.connect(ip);
- ftpClient.login(username, password);
- reply = ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftpClient.disconnect();
- }
- System.out.println(”sub_path==============”+sub_path);
- // 对目录进行转换
- if (ftpClient.changeWorkingDirectory(sub_path)) {
- } else {
- ftpClient.disconnect();
- ftpClient = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- if (0 < i–) {
- try {
- Thread.sleep(10000);
- continue;
- } catch (Exception ex) {
- }
- }
- }
- i = 0;
- }
- }
- }
- /**
- * 文件上传
- * @param ip
- * @param port
- * @param username
- * @param password
- * @param sub_path 远程文件上传目录
- * @param localFilePath 本地文件存放路径、、
- * @param newFileName 远程生成的文件路径和文件名
- * @throws Exception
- */
- public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
- BufferedInputStream buffIn = null;
- try {
- connectServer(ip,port,username,password,sub_path); //连接服务器
- System.out.println(”start upload”);
- buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
- System.out.println(”find localFilePath success”);
- ftpClient.storeFile(newFileName, buffIn);
- System.out.println(”upload success”);
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- } finally {
- try {
- if (buffIn != null)
- buffIn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- *
- * Definition: 读取txt文件,存放到list中,以便于读取
- * author: xiehaoyu
- * Created date: 2013-6-14
- * @param readTxt
- * @return
- */
- public static List<String> readTxt(String readTxt){
- BufferedReader br = null;
- List<String> list = new ArrayList<String>();
- try {
- br = new BufferedReader(new InputStreamReader(new FileInputStream(
- new File(readTxt))));
- String temp = br.readLine();
- while (temp != null) {
- String[] str=temp.toString().trim().split(”\\|”);
- for(String s : str){
- if(!“”.equals(s))
- list.add(s);
- }
- temp=br.readLine();
- }
- br.close();
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- return list;
- }
- public void copyFile(String oldPath, String newPath) {
- try {
- int bytesum = 0;
- int byteread = 0;
- File oldfile = new File(oldPath);
- if (oldfile.exists()) { //文件存在时
- InputStream inStream = new FileInputStream(oldPath); //读入原文件
- FileOutputStream fs = new FileOutputStream(newPath);
- byte[] buffer = new byte[1444];
- while ( (byteread = inStream.read(buffer)) != -1) {
- bytesum += byteread; //字节数 文件大小
- System.out.println(bytesum);
- fs.write(buffer, 0, byteread);
- }
- inStream.close();
- }
- }
- catch (Exception e) {
- System.out.println(”复制单个文件操作出错”);
- e.printStackTrace();
- }
- }
- public void delFile(String filePathAndName) {
- try {
- String filePath = filePathAndName;
- filePath = filePath.toString();
- java.io.File myDelFile = new java.io.File(filePath);
- myDelFile.delete();
- }
- catch (Exception e) {
- System.out.println(”删除文件操作出错”);
- e.printStackTrace();
- }
- }
- /**
- * 文件下载。。
- * @param url ftp ip
- * @param port ftp端口
- * @param username
- * @param password
- * @param remotePath 下载路径
- * @param fileName 下载文件中包含什么文件名
- * @param localPath 本地存放路径
- * @return
- */
- public static boolean downFile(
- String url,
- int port,
- String username,
- String password,
- String remotePath,
- String fileName,
- String localPath){
- boolean success = false;
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- ftp.connect(url, port);
- //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftp.login(username, password);//登录
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- return success;
- }
- ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
- FTPFile[] fs = ftp.listFiles();
- TfpTools fu=new TfpTools();
- for(FTPFile ff:fs){
- if(ff.getName().contains(fileName)){
- if(fu.ToDetermineWhetherAFileExists(ff.getName())){
- File localFile = new File(localPath+“/”+ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftp.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- }
- ftp.logout();
- success = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return success;
- }
- public boolean ToDetermineWhetherAFileExists(String fileName){
- boolean flag=true;
- Vector<String> v=new Vector<String>();
- v=GetTestXlsFileName(”c:/JX_jiekou/src/backups”);
- for(int i=0;i<v.size();i++){
- String str=(String)v.elementAt(i);
- if(str.equals(fileName)){
- flag=false;
- }
- }
- return flag;
- }
- /**
- * 读取本地某个目录下,所有txt文件的文件名
- * @param fileAbsolutePath 本地文件目录。
- * @return
- */
- public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
- Vector<String> vecFile = new Vector<String>();
- File file = new File(fileAbsolutePath);
- File[] subFile = file.listFiles();
- for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
- // 判断是否为文件夹
- if (!subFile[iFileLength].isDirectory()) {
- String fileName = subFile[iFileLength].getName();
- // 判断是否为.txt结尾
- if (fileName.trim().toLowerCase().endsWith(“.txt”)) {
- vecFile.add(fileName);
- }
- }
- }
- return vecFile;
- }
- public boolean truncateTable(String tableName){
- Connection conn=null;
- Statement sm=null;
- String sql=”truncate table ”+tableName;
- try {
- conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
- sm=conn.createStatement();
- sm.executeUpdate(sql);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return true;
- }
- public void closeConnect() {
- try {
- if (ftpClient != null) {
- ftpClient.logout();
- ftpClient.disconnect();
- ftpClient=null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class TfpTools {
//连接ftp
private FTPClient ftpClient = null;
// public static String ip = "117.21.208.37";
// public static int port = 21;
// public static String username = "eftp";
// public static String password = "e1f2t3p4";
// public static String sub_path = "/opt/tomcat/webapps/photocdn/msgdata/";
/**
* 连接ftp
*/
public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
int i = 10;
if (ftpClient == null) {
int reply;
while (i > 0) {
try {
ftpClient = new FTPClient();
if (port != 21)
ftpClient.connect(ip, port);
else
ftpClient.connect(ip);
ftpClient.login(username, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
System.out.println("sub_path=============="+sub_path);
// 对目录进行转换
if (ftpClient.changeWorkingDirectory(sub_path)) {
} else {
ftpClient.disconnect();
ftpClient = null;
}
} catch (Exception e) {
e.printStackTrace();
if (0 < i--) {
try {
Thread.sleep(10000);
continue;
} catch (Exception ex) {
}
}
}
i = 0;
}
}
}
/**
* 文件上传
* @param ip
* @param port
* @param username
* @param password
* @param sub_path 远程文件上传目录
* @param localFilePath 本地文件存放路径、、
* @param newFileName 远程生成的文件路径和文件名
* @throws Exception
*/
public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
BufferedInputStream buffIn = null;
try {
connectServer(ip,port,username,password,sub_path); //连接服务器
System.out.println("start upload");
buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
System.out.println("find localFilePath success");
ftpClient.storeFile(newFileName, buffIn);
System.out.println("upload success");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (buffIn != null)
buffIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* Definition: 读取txt文件,存放到list中,以便于读取
* author: xiehaoyu
* Created date: 2013-6-14
* @param readTxt
* @return
*/
public static List<String> readTxt(String readTxt){
BufferedReader br = null;
List<String> list = new ArrayList<String>();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
new File(readTxt))));
String temp = br.readLine();
while (temp != null) {
String[] str=temp.toString().trim().split("\\|");
for(String s : str){
if(!"".equals(s))
list.add(s);
}
temp=br.readLine();
}
br.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return list;
}
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
public void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
* 文件下载。。
* @param url ftp ip
* @param port ftp端口
* @param username
* @param password
* @param remotePath 下载路径
* @param fileName 下载文件中包含什么文件名
* @param localPath 本地存放路径
* @return
*/
public static boolean downFile(
String url,
int port,
String username,
String password,
String remotePath,
String fileName,
String localPath){
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
TfpTools fu=new TfpTools();
for(FTPFile ff:fs){
if(ff.getName().contains(fileName)){
if(fu.ToDetermineWhetherAFileExists(ff.getName())){
File localFile = new File(localPath+"/"+ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
public boolean ToDetermineWhetherAFileExists(String fileName){
boolean flag=true;
Vector<String> v=new Vector<String>();
v=GetTestXlsFileName("c:/JX_jiekou/src/backups");
for(int i=0;i<v.size();i++){
String str=(String)v.elementAt(i);
if(str.equals(fileName)){
flag=false;
}
}
return flag;
}
/**
* 读取本地某个目录下,所有txt文件的文件名
* @param fileAbsolutePath 本地文件目录。
* @return
*/
public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
Vector<String> vecFile = new Vector<String>();
File file = new File(fileAbsolutePath);
File[] subFile = file.listFiles();
for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
// 判断是否为文件夹
if (!subFile[iFileLength].isDirectory()) {
String fileName = subFile[iFileLength].getName();
// 判断是否为.txt结尾
if (fileName.trim().toLowerCase().endsWith(".txt")) {
vecFile.add(fileName);
}
}
}
return vecFile;
}
public boolean truncateTable(String tableName){
Connection conn=null;
Statement sm=null;
String sql="truncate table "+tableName;
try {
conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
sm=conn.createStatement();
sm.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
ftpClient=null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<div id="digg" articleid="24458469">
<dl id="btnDigg" class="digg digg_disable" onclick="btndigga();">
<dt>顶</dt>
<dd>0</dd>
</dl>
<dl id="btnBury" class="digg digg_disable" onclick="btnburya();">
<dt>踩</dt>
<dd>0</dd>
</dl>
</div>
<div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank"> </a> </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank"> </a></div>
<script type="text/javascript">
function btndigga() {
$(".tracking-ad[data-mod='popu_222'] a").click();
}
function btnburya() {
$(".tracking-ad[data-mod='popu_223'] a").click();
}
</script>
<div style="clear:both; height:10px;"></div>
<div class="similar_article">
<h4></h4>
<div class="similar_c" style="margin:20px 0px 0px 0px">
<div class="similar_c_t">
相关文章推荐
</div>
<div class="similar_wrap tracking-ad" data-mod="popu_36">
<ul class="similar_list fl">
</ul>
<ul class="similar_list fr">
</ul>
</div>
</div>
</div>