package comm.ftp;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; /**
* 该类为FTP相关的工具类
*
* @author wxq
*
*/
public class FtpUtil {
FTPClientConfig config = null;
FTPClient ftpClient = null;
String serverIp = "";// ftp服务器ip地址
int serverPort = 0;// ftp服务器端口
String usrName = "";// ftp用户名
String usrPwd = "";// ftp用户密码
String baseWorkDirectory = "";// 基本工作目录
int fileType = FTP.BINARY_FILE_TYPE;// 上传下载文件方式,默认使用二进制流
// 本地编码字符串编码
String localCharset = "UTF-8";
// FTP服务器端字符串编码
String serverCharset = "ISO-8859-1"; public FtpUtil(String serverIp, int serverPort, String usrName,
String usrPwd, String baseWorkDirectory, int fileType) {
super();
this.serverIp = serverIp;
this.serverPort = serverPort;
this.usrName = usrName;
this.usrPwd = usrPwd;
this.baseWorkDirectory = baseWorkDirectory;
this.fileType = fileType;
} /**
* 使用默认值,生成FTPClientConfig对象
*/
public void setFtpClientConfigByDefault() {
config = new FTPClientConfig();
} /**
* 使用参数指定的值生成FTPClientConfig对象
*
* @param isParamsActived
* 标记是否使用后面参数,false则不使用,且使用默认值构造一个FTPClientConfig对象
* @param osType
* FTPClientConfig.SYST_NT FTPClientConfig.SYST_UNIX
* @param serverLanguageCode
* @param defaultDateFormatStr
* @param recentDateFormatStr
* @param serverTimeZoneId
* @return
*/
public void setFtpClientConfig(String osType, String serverLanguageCode,
String defaultDateFormatStr, String recentDateFormatStr,
String serverTimeZoneId) {
try {
if (!osType.equals("")) {
config = new FTPClientConfig(osType);
}
if (!serverLanguageCode.equals("")) {
config.setServerLanguageCode(serverLanguageCode);
}
if (!defaultDateFormatStr.equals("")) { config.setDefaultDateFormatStr(defaultDateFormatStr);
}
if (!recentDateFormatStr.equals("")) { config.setRecentDateFormatStr(recentDateFormatStr);
}
if (!serverTimeZoneId.equals("")) { config.setServerTimeZoneId(serverTimeZoneId);
} } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} /**
* 连接FTP服务器,并登录,切换至基本工作目录(通常为当前用户的根目录)
*
*/
public void connectServer() {
try {
ftpClient = new FTPClient();
if (config != null) {
ftpClient.configure(config);
int reply;
ftpClient.connect(serverIp, serverPort);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("FTP server refused connection");
} else {
// set file type
// ftpClient.setFileType(fileType);
if (ftpClient.login(usrName, usrPwd)) {
System.out.println("login success");
}
ftpClient.changeWorkingDirectory(baseWorkDirectory);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
} /**
* 上传文件至Ftp用户根目录下的指定目录,如果subDirectory.equals("")为true, 则上传文件存放到当前用户的根目录
*
* @param subDirectory
* 子目录
* @param storeName
* 上传文件在FTP服务器上的存储名字
* @param file
* 上传文件
* @return
*/
public boolean uploadFileToFtpServer(String subDirectory, String storeName,
File file) {
// 上传文件成功标记
boolean isUploadSuccess = false;
FileInputStream fin = null;
try {
if (file.exists()) {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
storeName=new String(storeName.getBytes(localCharset),serverCharset);
storeName = new String(storeName.getBytes(localCharset),
serverCharset);
storeName = this.handleStoreName(subDirectory, storeName);
fin = new FileInputStream(file);
// Stores a file on the server using the given name and taking
// input from the given InputStream.
if (ftpClient.storeFile(storeName, fin)) {
isUploadSuccess = true;
System.out.println("upload file to FTP server success");
}
} else {
System.out.println("upload file does not exsit");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return isUploadSuccess;
} /**
* 上传字符串至Ftp用户根目录下的指定目录下的指定文件,如果subDirectory.equals("")为true,
* 则上传文件存放到当前用户的根目录
*
* @param subDirectory
* 子目录,
* @param storeName
* 上传的字符串在FTP服务器上存储文件的名字
* @param uploadStr
* 上传的字符串
* @return
*/
public boolean uploadStringToFtpServer(String subDirectory,
String storeName, String uploadStr) {
// 上传成功标记
boolean isUploadSuccess = false;
ByteArrayInputStream bais = null;
try {
if (uploadStr != null) {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
storeName=new String(storeName.getBytes(localCharset),serverCharset);
storeName = this.handleStoreName(subDirectory, storeName);
bais = new ByteArrayInputStream(uploadStr.getBytes());
// Stores a file on the server using the given name and taking
// input from the given InputStream.
if (ftpClient.storeFile(storeName, bais)) {
isUploadSuccess = true;
System.out.println("upload String to FTP server success");
}
} else {
System.out.println("upload String is null");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return isUploadSuccess;
} /**
* 从FTP服务器下载文件到本地指定路径,当subDirectory.equals("")时,则在当前用户的根目录下去找要下载的文件
*
* @param subDirectory
* ftp服务器上存放要下载文件的子目录
* @param fileName
* 下载文件的名字
* @param localPath
* 本地存放路径
* @return 下载成功,返回true
*/
public boolean downFileFromFtpServer(String subDirectory, String fileName,
String localPath) {
FileOutputStream fos = null;
boolean isDownloadSuccess = false;
try {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
String baseWorkDir = ftpClient.printWorkingDirectory();
if (!subDirectory.equals("")) {
baseWorkDir = baseWorkDir + "/" + subDirectory;
}
ftpClient.changeWorkingDirectory(baseWorkDir); fos = new FileOutputStream(localPath + "/" + fileName);
fileName = new String(fileName.getBytes(localCharset),
serverCharset);
// Retrieves a named file from the server and writes it to the given
// OutputStream.
if (ftpClient.retrieveFile(fileName, fos)) {
isDownloadSuccess = true;
System.out.println("download from FTP server success");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return isDownloadSuccess;
} /**
* 下载Ftp服务器上指定目录下的所有文件(不包含文件夹)到本机的指定目录,子目录subDirectory.equals("")时, 则指定目录就是用户的根目录
*
* @param subDirectory
* ftp服务器上包含文件的子目录
* @param localPath
* @return
*/
public boolean downloadFilesFromFtpServer(String subDirectory,
String localPath) {
boolean isDownloadSuccess = false;
FileOutputStream fos = null;
try {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
String baseWorkDir = ftpClient.printWorkingDirectory();
if (!subDirectory.equals("")) {
baseWorkDir = baseWorkDir + "/" + subDirectory;
}
ftpClient.changeWorkingDirectory(baseWorkDir);
FTPFile[] files = ftpClient.listFiles();
if (files != null && files.length > 0) {
// 下载目录下所有文件
for (FTPFile file : files) {
if(file.isFile()){
String fileName = new String(file.getName().getBytes(
serverCharset), localCharset);
fos = new FileOutputStream(localPath + "/" + fileName);
if (ftpClient.retrieveFile(file.getName(), fos)) {
System.out.println("download file: " + fileName
+ " success");
}
fos.flush();
}
}
}
isDownloadSuccess = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return isDownloadSuccess;
} /**
* 删除ftp服务器上的指定目录下的某个文件
*
* @param subDirectory
* 子目录
* @param fileName
* 文件名
* @return 删除成功,返回true
*/
public boolean deleteFileInFtpServer(String subDirectory, String fileName) {
boolean isDeleteSuccess = false;
try {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
fileName = new String(fileName.getBytes(localCharset),
serverCharset);
fileName = this.handleStoreName(subDirectory, fileName);
if (ftpClient.deleteFile(fileName)) {
isDeleteSuccess = true;
System.out.println("delete file on ftp server success");
} else {
System.out.println("delete file on ftp server fail");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isDeleteSuccess;
} /**
* 删除指定目录下的所有文件,如果folderName为“”,则删除subDirectory下的所有文件(不包括文件夹)。
*
* @param subDirectory
* 子目录
* @param folderName
* 文件夹名称
* @return
*/
public boolean deleteFilesInFtpServer(String subDirectory, String folderName) {
boolean isDeleteSuccess = false;
try {
String baseWorkDir = ftpClient.printWorkingDirectory();
if (!subDirectory.equals("")) {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
baseWorkDir = baseWorkDir + "/" + subDirectory;
}
if (!folderName.equals("")) {
folderName=new String(folderName.getBytes(localCharset),serverCharset);
baseWorkDir = baseWorkDir + "/" + folderName;
}
ftpClient.changeWorkingDirectory(baseWorkDir);
FTPFile[] files = ftpClient.listFiles();
if (files != null) {
for (FTPFile file : files) {
ftpClient.deleteFile(file.getName());
}
isDeleteSuccess=true;
}
System.out.println("delete files in ftp server success");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("delete files in ftp server exception: "+e.getMessage());
}
return isDeleteSuccess;
} /**
* 在用户的根目录下创建指定文件夹,如果subDirectory是一个目录则依次创建各级文件夹。如果文件夹存在,则返回false
*
* @param subDirectory
* 子目录
* @return 成功返回true
*/
public boolean createDirInBaseWorkDir(String subDirectory) {
boolean isCreateSuccess = false;
try {
if (!subDirectory.equals("")) {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
if (ftpClient.makeDirectory(subDirectory)) {
isCreateSuccess = true;
System.out
.println("create new directory in base work directory success");
} else {
System.out
.println("create new directory fail,the directory exsited");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isCreateSuccess;
} /**
* 删除用户根目录下的指定文件夹,如果subDirectory是一个路径,则删除最低级的那个文件夹;如果文件夹不存在则返回false。
* 如果文件夹不为空,则返回false
*
* @param subDirectory
* @return
*/
public boolean rmDirInBaseWorkDir(String subDirectory) {
boolean isRmDirSuccess = false;
try {
subDirectory=new String(subDirectory.getBytes(localCharset),serverCharset);
if (ftpClient.removeDirectory(subDirectory)) {
isRmDirSuccess = true;
System.out
.println("remove directory in base work directory success");
} else {
System.out
.println("remove directory in base work directory fail");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isRmDirSuccess;
} /**
* 该方法用于处理文件时,对子目录和文件名进行处理
*
* @param subDirectory
* 子目录
* @param storeName
* 文件名
* @return 返回处理后可能带有路径的文件名
*/
private String handleStoreName(String subDirectory, String storeName) {
// 子目录是否存在标记
boolean isSubDirectoryExsit = false;
try {
// 此处判断是否要生成子目录,存在则不创建
FTPFile[] dirs = ftpClient.listDirectories();
if (dirs != null && dirs.length > 0) {
for (int i = 0; i < dirs.length; i++) {
if (dirs[i].getName().equals(subDirectory)) {
isSubDirectoryExsit = true;
}
break;
}
}
dirs = null;
if (!isSubDirectoryExsit && !subDirectory.equals("")) {
ftpClient.makeDirectory(subDirectory);
storeName = subDirectory + "/" + storeName;
}
if (isSubDirectoryExsit && !subDirectory.equals("")) {
storeName = subDirectory + "/" + storeName;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return storeName;
} }

java 操作FTP的更多相关文章

  1. java操作FTP的一些工具方法

    java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...

  2. Java操作FTP工具类(实例详解)

    这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包  工具类 package com.zit.ftp; import java.io.File; import java.i ...

  3. java操作FTP,实现文件上传下载删除操作

    上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...

  4. Java操作FTP,从FTP上读取指定文件,把指定文件上传到FTP

    需要添加的依赖 <!-- https://mvnrepository.com/artifact/commons-net/commons-net --> <dependency> ...

  5. Java实现FTP跨服务器文件操作

    在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传.文件下载.文件删除等.跨服务器文件操作一般是需要FT ...

  6. Java实现FTP文件与文件夹的上传和下载

    Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...

  7. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  8. 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等

    记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...

  9. Java操作Sqlite数据库-jdbc连接

    Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...

随机推荐

  1. TIME_WAIT问题总结

         最近用http_load做压测,跑出来一大串"Cannot assign requested address "的错误,查了一下,是TIME_WAIT过多导致的.因为短时 ...

  2. JavaWeb之JSP技术总结

    刚接触JSP技术的时候让我想起了在大学学的Asp+VBScript,记得当时我还用aspstudy做了一个小的新闻发布系统作为期末作品,也正是在那时候在卢哥卢老师的指导下走向编程的道路,对编程越来越感 ...

  3. 享受release版本发布的好处的同时也应该警惕release可能给你引入一些莫名其妙的大bug

    一般我们发布项目的时候通常都会采用release版本,因为release会在jit层面对我们的il代码进行了优化,比如在迭代和内存操作的性能提升方面,废话不多说, 我先用一个简单的“冒泡排序”体验下r ...

  4. MFC画笔作用域的问题

    今天发现了程序中的一个BUG.功能是在鼠标经过图形时,对图形进行加粗重绘.默认使用白色画刷.为防止白色背景下看不清,在白色背景下改用黑色画刷.代码如下 CPen* pOldPen;if (pDC-&g ...

  5. pxe+kickstart cobbler无人值守装机

    环境准备: 一台服务器 [root@admin tftpboot]# cat /etc/redhat-release CentOS Linux release 7.2.1511 (Core) [roo ...

  6. Java结合WebUploader文件上传

    之前自己写小项目的时候也碰到过文件上传的问题,没有找到很好的解决方案.虽然之前网找各种解决方案的时候也看到过WebUploader,但没有进一步深究.这次稍微深入了解了些,这里也做个小结. 简单的文件 ...

  7. go单元测试进阶篇

    作者介绍:熊训德(英文名:Sundy),16年毕业于四川大学大学并加入腾讯.目前在腾讯云从事hadoop生态相关的云存储和计算等后台开发,喜欢并专注于研究大数据.虚拟化和人工智能等相关技术. 本文档说 ...

  8. socket bind详解

    http://www.cnblogs.com/nightwatcher/archive/2011/07/03/2096717.html 在最开始接触bind的时候,只是在写基于tcp的server端的 ...

  9. CentOS 7 Root用户密码重置 2017-04-02

    跨平台系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#linux 开机的时候按e (如果正在使用,你可以输入reboot,然后赶紧按回车键,也可 ...

  10. ubuntu 12.04 x86_64:java.lang.UnsatisfiedLinkError: Could not load SWT library. Reasons

    sy@sy-Aspire-:~$ .0_155965261/configuration/.log !SESSION -- ::39.595 ------------------------------ ...