java 操作FTP
- 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的更多相关文章
- java操作FTP的一些工具方法
java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...
- Java操作FTP工具类(实例详解)
这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包 工具类 package com.zit.ftp; import java.io.File; import java.i ...
- java操作FTP,实现文件上传下载删除操作
上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...
- Java操作FTP,从FTP上读取指定文件,把指定文件上传到FTP
需要添加的依赖 <!-- https://mvnrepository.com/artifact/commons-net/commons-net --> <dependency> ...
- Java实现FTP跨服务器文件操作
在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传.文件下载.文件删除等.跨服务器文件操作一般是需要FT ...
- Java实现FTP文件与文件夹的上传和下载
Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等
记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...
- Java操作Sqlite数据库-jdbc连接
Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...
随机推荐
- Ionic android 底部tabs
ionic android tabs 默认显示在上部,如果要跟苹果一起统一在底部,那么可以在app.js添加配置 .config(function($ionicConfigProvider) { $i ...
- Android Crash 全局捕获
Android Crash 全局捕获 首先应该明白的一点是,Android在崩溃后会重新启动崩溃时的那个Activity,如果你的Activity在初始化的时候就直接崩溃,那么你将连续得到 Crash ...
- python 接口自动化测试(四)
说完了SOAP协议的接口自动化 该说下http协议的接口测试了 HttpService.py import requests import sys reload(sys) sys.setdefault ...
- shiro学习笔记_0100_shiro简介
前言:第一次知道shiro是2016年夏天,做项目时候我要写springmvc的拦截器,申哥看到后,说这个不安全,就给我捣鼓了shiro,我就看了下,从此认识了shiro.此笔记是根据网上的视频教程记 ...
- java中String s = new String("abc")创建了几个对象?
答案是两个,现在我们具体的说一下: String s = new String("abc");一.我们要明白两个概念,引用变量和对象,对象一般通过new在堆中创建,s只是一个引用变 ...
- 二级C考点汇总
1.变量命名的合法性2.数据类型的转换,分为强类型和隐式类型3.字符串:字符串的声明.定义和使用,通常结合数组和指针 4.数组:下标的转换及数组的顺序存储5.函数:声明.定义.调用,递归函数(如菲薄纳 ...
- Bootstrap 组件之 Navbar
一.简介 Navbar 指导航条,它在移动设备上显示为折叠状态,在宽屏幕上水平展开.这里 是一个线上例子. 响应式导航条依赖 collapse 插件,定制 Bootstrap 时务必要包含. {设备的 ...
- python复习。知识点小记
1.对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符: >>> ord('A') >>> ord('中' ...
- 使用github+hexo搭建博客笔记
听说github上可以搭博客,而且不用自己提供空间和维护,哈哈哈 作为一名程序猿,github搭博客对我有种神奇的吸引力,赶紧动手试一试 关于如何使用hexo搭建博客网上好的教程多如牛毛,而且这篇博客 ...
- 自适应滤波:最小均方误差滤波器(LMS、NLMS)
作者:桂. 时间:2017-04-02 08:08:31 链接:http://www.cnblogs.com/xingshansi/p/6658203.html 声明:欢迎被转载,不过记得注明出处哦 ...