Java-FtpUtil工具类
package cn.ipanel.app.newspapers.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
/**
* FTP工具类<br>
* 注:上传,可上传文件、文件夹;下载,仅实现下载文件功能,不能识别子文件夹
* @version 1.0.0
*/
public class FtpUtil
{
private static Logger logger = Logger.getLogger(FtpUtil.class);
private FtpClient ftpClient;
/**
* 连接FTP服务器,使用默认FTP端口
* @since
* @param serverIp
* 服务器Ip地址
* @param user
* 登陆用户
* @param password
* 密码
* @throws IOException
*/
public void connect(String serverIp, String user, String password) throws Exception
{
try
{
// serverIp:FTP服务器的IP地址;
// user:登录FTP服务器的用户名
// password:登录FTP服务器的用户名的口令;
ftpClient = new FtpClient();
ftpClient.openServer(serverIp);
ftpClient.login(user, password);
// 用二进制传输数据
ftpClient.binary();
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 连接ftp服务器,指定端口
* @since
* @param serverIp
* @param port
* 服务器FTP端口号
* @param user
* @param password
* @throws IOException
*/
public void connect(String serverIp, int port, String user, String password) throws Exception
{
try
{
// serverIp:FTP服务器的IP地址;
// post:FTP服务器端口
// user:登录FTP服务器的用户名
// password:登录FTP服务器的用户名的口令;
ftpClient = new FtpClient();
ftpClient.openServer(serverIp, port);
ftpClient.login(user, password);
// 用2进制传输数据
ftpClient.binary();
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 断开与ftp服务器的连接
* @since
* @throws IOException
*/
public void disConnect() throws Exception
{
try
{
if (ftpClient != null)
{
ftpClient.sendServer("QUIT\r\n");
ftpClient.readServerResponse();
// ftpClient.closeServer();
}
}
catch (IOException ex)
{
logger.error("DisConnect to FTP server failure! Detail:", ex);
throw new Exception(ex);
}
}
/**
* 上传文件至FTP服务器,保持原文件名
*
* @throws java.lang.Exception
* @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
* @param localFile
* 待上传的本地文件
*/
public long upload(File localFile) throws Exception
{
if (localFile == null)
{
return -1;
}
return this.upload(localFile, localFile.getName());
}
/**
* 上传文件至FTP服务器,保持原文件名
*
* @throws java.lang.Exception
* @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
* @param localFilePath
* 待上传的本地文件路径
*/
public long upload(String localFilePath) throws Exception
{
return this.upload(new File(localFilePath));
}
/**
* 上传文件至FTP服务器,并重命名文件
*
* @throws java.lang.Exception
* @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
* @param localFilePath
* 待上传的本地文件路径
* @param rename
* 远程文件重命名
*/
public long upload(String localFilePath, String rename) throws Exception
{
return this.upload(new File(localFilePath), rename);
}
/**
* 上传文件至FTP服务器,并重命名文件
*
* @throws java.lang.Exception
* @return -1 文件不存在或不能读取; >0 成功上传,返回文件的大小
* @param localFile
* 待上传的本地文件
* @param rename
* 远程文件重命名
*/
public long upload(File localFile, String rename) throws Exception
{
if (localFile == null || !localFile.exists() || !localFile.canRead())
{
return -1;
}
long fileSize = localFile.length();
try
{
if (localFile.isDirectory())
{
ftpClient.sendServer("XMKD " + rename + "\r\n");
ftpClient.readServerResponse();
File[] subFiles = localFile.listFiles();
ftpClient.cd(rename);
try
{
for (int i = 0; i < subFiles.length; i++)
{
fileSize += upload(subFiles[i]);
}
}
finally
{
ftpClient.cdUp();
}
}
else
{
this.writeFileToServer(localFile, rename);
}
return fileSize;
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 从ftp下载文件到本地
*
* @throws java.lang.Exception
* @return
* @param localFilePath
* 本地生成的文件名
* @param remoteFilePath
* 服务器上的文件名
*/
public long download(String remoteFilePath, String localFilePath) throws Exception
{
long result = 0;
TelnetInputStream tis = null;
RandomAccessFile raf = null;
DataInputStream puts = null;
try
{
tis = ftpClient.get(remoteFilePath);
raf = new RandomAccessFile(new File(localFilePath), "rw");
raf.seek(0);
int ch;
puts = new DataInputStream(tis);
while ((ch = puts.read()) >= 0)
{
raf.write(ch);
}
}
catch (Exception ex)
{
logger.error("Downloading file failure! Detail:", ex);
throw new Exception(ex);
}
finally
{
try
{
puts.close();
if (tis != null)
{
tis.close();
}
if (raf != null)
{
raf.close();
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
return result;
}
/**
* 设置FTP服务器的当前路径<br>
* 可以是绝对路径,也可以是相对路径
* @since
* @param dirPath
* 服务器文件夹路径,空代表ftp根目录
* @throws IOException
*/
public void cd(String dirPath) throws Exception
{
try
{
// path:FTP服务器上的路径,是ftp服务器下主目录的子目录
if (dirPath != null && dirPath.length() > 0)
{
ftpClient.cd(dirPath);
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 在服务器上创建指定路径的目录,并转到此目录
* @since
* @param dirPath
* @throws Exception
*/
public void mkd(String dirPath) throws Exception
{
try
{
if (dirPath != null && dirPath.length() > 0)
{
StringTokenizer st = new StringTokenizer(dirPath.replaceAll("\\\\", "/"), "/");
String dirName = "";
while (st.hasMoreElements())
{
dirName = (String) st.nextElement();
ftpClient.sendServer("XMKD " + dirName + "\r\n");
ftpClient.readServerResponse();
ftpClient.cd(dirName);
}
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 删除FTP服务器目录
* @since
* @param directory
* @throws Exception
*/
public void rmd(String directory) throws Exception
{
try
{
if (directory != null && directory.length() > 0)
{
ftpClient.cd(directory);
try
{
this.cld();
}
finally
{
ftpClient.cdUp();
}
ftpClient.sendServer("XRMD " + directory + "\r\n");
ftpClient.readServerResponse();
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 清空当前目录
* @since
* @throws Exception
*/
public void cld() throws Exception
{
// 删除文件
for (Iterator<String> it = getFileList().iterator(); it.hasNext();)
{
this.delf(it.next());
}
// 删除文件夹
for (Iterator<String> it = getDirList().iterator(); it.hasNext();)
{
this.rmd(it.next());
}
}
/**
* 删除FTP服务器文件
* @since
* @param filePath
* @throws Exception
*/
public void delf(String filePath) throws Exception
{
try
{
if (filePath != null && filePath.length() > 0)
{
ftpClient.sendServer("DELE " + filePath + "\r\n");
ftpClient.readServerResponse();
}
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
/**
* 以指定文件名,将本地文件写到FTP服务器
* @since
* @param localFile
* 待上传的本地文件
* @param fileName
* 写入远程FTP服务器的文件名
* @throws Exception
*/
private void writeFileToServer(File localFile, String fileName) throws Exception {
TelnetOutputStream tos = null;
FileInputStream fis = new FileInputStream(localFile);
try {
tos = ftpClient.put(fileName);
byte[] bytes = new byte[102400];
int c;
while ((c = fis.read(bytes)) != -1) {
tos.flush();
tos.write(bytes, 0, c);
}
} catch (Exception ex) {
throw new Exception(ex);
} finally {
if (fis != null) {
fis.close();
}
if (tos != null) {
tos.flush();
tos.close();
}
}
}
/**
* 取得FTP上某个目录下的所有文件名列表
*
* @since
* @return
* @throws Exception
*/
public List<String> getFileList() throws Exception
{
List<String> fileList = new ArrayList<String>();
BufferedReader br = null;
try
{
String fileItem;
br = new BufferedReader(new InputStreamReader(ftpClient.list()));
while ((fileItem = br.readLine()) != null)
{
if (fileItem.startsWith("-") && !fileItem.endsWith(".") && !fileItem.endsWith(".."))
{
fileList.add(parseFileName(fileItem));
}
}
}
catch (Exception ex)
{
logger.error("Failure to get directory list from ftp server!", ex);
throw new Exception(ex);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
}
return fileList;
}
/**
* 取得FTP上某个目录下的所有子文件夹名列表
*
* @since
* @return
* @throws Exception
*/
public List<String> getDirList() throws Exception
{
List<String> dirList = new ArrayList<String>();
BufferedReader br = null;
try
{
String fileItem;
br = new BufferedReader(new InputStreamReader(ftpClient.list()));
while ((fileItem = br.readLine()) != null)
{
if (fileItem.startsWith("d") && !fileItem.endsWith(".") && !fileItem.endsWith(".."))
{
dirList.add(parseFileName(fileItem));
}
}
}
catch (Exception ex)
{
logger.info("Failure to get directory list from ftp server!", ex);
throw new Exception(ex);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
}
return dirList;
}
/**
* 从文件信息中解析出文件(文件夹)名
*
* @since
* @param fileItem
* @return
* @throws Exception
*/
private String parseFileName(String fileItem) throws Exception
{
StringTokenizer st = new StringTokenizer(fileItem);
int index = 0;
while (st.hasMoreTokens())
{
if (index < 8)
{
st.nextToken();
}
else
{
return st.nextToken("").trim();
}
index++;
}
return null;
}
/**
* 上传下载测试
*
* @since
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
FtpUtil ftp = new FtpUtil();
try
{
// 连接ftp服务器
ftp.connect("xx.xx.xx.xx", "ftp", "ftp");
// 上传文件
ftp.cd("/home/sasftp");
// ftp.cld();
// long fileSize = ftp.upload("D:/视频",
// "xufeitewwst");
// if (fileSize == -1) {
// logger.info("Uploading file failure! Because file do not exists!");
// } else if (fileSize == -2) {
// logger.info("Uploading file failure! Because file is empty!");
// } else {
// logger.info("Uploading file success! File size: " + fileSize);
// }
// 取得bbbbbb文件夹下的所有文件列表,并下载到本地保存
List<String> list = new ArrayList<String>();
list.add("czybxw.txt");
list.add("zjyb.txt");
for (int i = 0; i < list.size(); i++)
{
String fileName = (String) list.get(i);
System.out.println(fileName);
ftp.download(fileName, "E:\\text" + File.separator + fileName);
}
}
catch (Exception ex)
{
logger.error("Uploading file failure! Detail:", ex);
}
finally
{
ftp.disConnect();
}
}
}
Java-FtpUtil工具类的更多相关文章
- Java Properties工具类详解
1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- MinerUtil.java 爬虫工具类
MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
- 小记Java时间工具类
小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...
- Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie
Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...
- UrlUtils工具类,Java URL工具类,Java URL链接工具类
UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...
- java日期工具类DateUtil-续一
上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...
随机推荐
- 网站循环加载监控-C#
背景: 公司有一个报表的网站,服务器或系统不太稳定,导致客户有时候查看报表网址的时候网站打不开或者打开时间过长,影响用户体验 需求: 通过程序循环打开网址了解加载情况,使用谷歌浏览器内核.,程序开发不 ...
- PAT B1006 换个格式输出整数 (15)
AC代码 #include <cstdio> const int max_n = 3; char radix[max_n] = {' ', 'S', 'B'}; int ans[max_n ...
- python项目内import其他内部package的模块的正确方法
转载 :https://blog.csdn.net/u011089523/article/details/52931844 本文主要介绍如何在一个Python项目中,优雅的实现项目内各个package ...
- yum更新出错-解决
Total download size: 14 MIs this ok [y/d/N]: 命令里已经yum install -y了,但是还是需要选择Y,N没有自动执行,请问这个要怎么破. PS:我是在 ...
- cent0S 设置静态ip
TYPE=EthernetPROXY_METHOD=noneBROWSER_ONLY=noBOOTPROTO=static # static ip,#BOOTPROTO=dhcp # dynamic ...
- spring jpa 学习笔记(一) 之集成
一.pom 配置 <?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apa ...
- 14-Perl 引用
1.Perl 引用引用就是指针.Perl 引用是一个标量类型,可以指向变量.数组.哈希表(也叫关联数组)甚至子程序,可以应用在程序的任何地方.2.创建引用定义变量的时候,在变量名前面加个\,就得到了这 ...
- 7.bash作业控制
7.作业控制本节讨论作业控制是什么.它怎么工作.以及 Bash 里面怎么使用这些功能7.1 作业控制基础作业控制是指有选择的停止(暂停)并在后来继续(恢复)执行某个进程的能力.通常,用户通过 Bash ...
- c++ 性能优化策略
c++ 性能优化策略 作者:D_Guco 来源:CSDN 原文:https://blog.csdn.net/D_Guco/article/details/75729259 1 关于继承:不可否认良好的 ...
- Linux--目录属性
目录的读属性:表示具有读取目录结构清单的权限.使用ls命令可以将该目录中的文件和子目录的内容列出来. 目录的写属性:表示具有更改目录结构清单的权限.包括以下操作: 建立新的文件与目录 删除已经存在的文 ...