Java实现FTP跨服务器文件操作
在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传、文件下载、文件删除等。跨服务器文件操作一般是需要FTP协议和SFTP协议两种,现在就通过Java实现FTP协议的文件上传。要实现FTP操作文件需要引入jar包: commons-net-1.4.1.jar
具体代码如下:
import java.io.*;
import java.net.MalformedURLException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* ftp 文件上传工具类
* 所需jar包(commons-net-1.4.1.jar)
*/
public class FtpUtils {
//ftp服务器地址
public String hostname ;
//ftp服务器端口号默认为21
public Integer port ;
//ftp登录账号
public String username ;
//ftp登录密码
public String password ;
//FTP客户端对象
public FTPClient ftpClient = null;
//构造方法
public FtpUtils(String hostname,Integer port,String username,String password){
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println("connect failed...ftp服务器:"+this.hostname+":"+this.port);
}
System.out.println("connect successfu...ftp服务器:"+this.hostname+":"+this.port);
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
flag =ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 待上传文件输入流 *
* @return
*/
public boolean uploadFileByInputStream( String pathname, String fileName,InputStream inputStream){
boolean flag = false;
try{
System.out.println("开始上传文件");
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
flag =ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
boolean flag = false;
try{
System.out.println("开始上传文件");
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
flag = ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 改变目录路径
* @param directory
* @return
*/
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
System.out.println("进入文件夹" + directory + " 成功!");
} else {
System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
/**
* 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param remote
* @return
* @throws IOException
*/
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
/**
* 判断ftp服务器文件是否存在
* @param path
* @return
* @throws IOException
*/
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
/**
* 创建目录
* @param dir
* @return
*/
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println("创建文件夹" + dir + " 成功!");
} else {
System.out.println("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String filename, String localpath){
boolean flag = false;
OutputStream os=null;
try {
System.out.println("开始下载文件");
initFtpClient();
ftpClient.enterLocalPassiveMode();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
flag = ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String filename,String dbFilename, String localpath){
boolean flag = false;
OutputStream os=null;
try {
System.out.println("开始下载文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
File localFile = new File(localpath + "/" + dbFilename);
os = new FileOutputStream(localFile);
flag = ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/** * 获取ftp文件输入流 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @return */
public InputStream downloadFile(String pathname, String filename){
InputStream fileStream = null;
try {
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
ftpClient.enterLocalPassiveMode();
fileStream = ftpClient.retrieveFileStream(new String(file.getName().getBytes("GBK"),"ISO8859-1"));
break;
}
}
ftpClient.logout();
} catch (Exception e) {
System.out.println("获取下载的文件流");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return fileStream;
}
/** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return */
public boolean deleteFile(String pathname, String filename){
boolean flag = false;
try {
System.out.println("开始删除文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalPassiveMode();
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
System.out.println("删除文件成功");
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return flag;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
FtpUtils ftp =new FtpUtils("192.168.1.123",21,"aaa","aa123");
//ftp.downloadFile("ftpFile/ss/model", "ceshi.xlsx","E:/abc");
//ftp.deleteFile("ftpFile/ss/model","ceshi.txt");
/*InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File("E:/abc/abc.txt"));
ftp.uploadFileByInputStream("ftpFile/ss/model", "abc.txt", inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
boolean flag = ftp.uploadFile( "/", "bbb.txt","E:/abc/bbb.txt");
System.out.println(flag);
/*InputStream downloadFile = ftp.downloadFile("/home/aaa/ftpFile/data/policy/model", "Report1.doc");
System.out.println(downloadFile);
FtpUtils _ftp =new FtpUtils("192.168.1.123",21,"aaa","aa123");
_ftp.uploadFile("ftpFile/data/model","Report1.doc", downloadFile);*/
//ftp.downloadFile("ftpFile/data/policy/model", "Report1.doc","2e0ee9b1476c4bd3bb0cad5ecef6d4c3.pdf", "D:/test/uploadfile/modelfile/");
//ftp.deleteFile("ftpFile/data", "123.docx");
System.out.println("ok");
}
}
Java实现FTP跨服务器文件操作的更多相关文章
- 前后端分离跨服务器文件上传-Java SpringMVC版
近来工作上不上特别忙,加上对后台java了解一点,所以就抽时间,写了一个java版本的前后端分离的跨服务器文件上传功能,包括前后端代码. 一.Tomcat服务器部分 1.Tomcat服务器 单独复制一 ...
- 通过cmd完成FTP上传文件操作
一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...
- ABAP服务器文件操作
转自http://blog.itpub.net/547380/viewspace-876667/ 在程序设计开发过程中,很多要对文件进行操作,这又分为对本地文件操作和服务器文件操作.对本地文件操作使用 ...
- java使用ftp上传文件
ftpServer是apache MINA项目的一个子项目,它实现了一个ftp服务器,与vsftpd是同类产品.Filezilla是一个可视化的ftp服务器. ftp客户端也有很多,如Filezill ...
- JAVA调用FTP上传文件
import java.io.File; import java.io.FileInputStream; import org.apache.commons.net.ftp.FTP; import o ...
- Java序列化与反序列化,文件操作
参考两篇博客: http://blog.csdn.net/moreevan/article/details/6697777 http://blog.csdn.net/moreevan/article/ ...
- 通过ftp同步服务器文件:遍历文件夹所有文件(含子文件夹、进度条);简单http同步服务器文件实例
该代码主要实现,指定ftp服务地址,遍历下载该地址下所有文件(含子文件夹下文件),并提供进度条显示:另外附带有通过http地址方式获取服务器文件的简单实例 废话不多说,直接上代码: 1.FTPHelp ...
- Java 之 File类(文件操作)
一.概述 java.io.File 类是文件和目录路径名册抽象表示,主要用于文件和目录的创建.查找和删除等操作. File类是一个与系统无关的类,任何的操作系统都可以使用这个类中的方法. 路径问题: ...
- 跨服务器sql操作
1.打开跨服务器功能 exec sp_configure 'show advanced options',1 reconfigure exec sp_configure 'Ad Hoc Distrib ...
随机推荐
- 实验二 C2C实践
实验二 C2C实践 [实验目的] 掌握网上购物的基本流程和C2C平台的运营 [实验条件] ⑴.个人计算机一台 ⑵.计算机通过局域网形式接入互联网. (3).奥派电子商务应用软件 [知识准备] 本实验 ...
- 用Docker容器安装Jenkins
先安装Docker 可以参考我的上一篇文章 链接 拉取Jenkins最新镜像,可跟版本号 不跟默认拉取最新镜像 docker pull jenkins/jenkins 创建JenKins的工作目录 m ...
- pytest文档49-命令行参数--tb的使用
前言 pytest 使用命令行执行用例的时候,有些用例执行失败的时候,屏幕上会出现一大堆的报错内容,不方便快速查看是哪些用例失败. --tb=style 参数可以设置报错的时候回溯打印内容,可以设置参 ...
- 【学习笔记】Min-max 容斥
经常和概率期望题相结合. 对于全序集合 \(S\),有: \[\max S=\sum\limits_{T\subseteq S,T\not=\varnothing}(-1)^{\vert T\vert ...
- 为Linux的文件管理器创建“在此打开终端”菜单
有些Linux的GUI文件管理器没有右键菜单"在此打开终端",或者有却不能自行指定某种终端. 因为文件夹也有其MIME类型(inode/directory),通过文件关联的方式,把 ...
- kali 運行 chrome
0x00前提 已經安裝好google chrome . 0x01 在終端執行命令: google-chrome,發現如圖: 錯誤提示:在root下只能使用 --no-sandbox選項來運行chrom ...
- python操作excel xlwt (转)
Python中xlrd和xlwt模块使用方法 阅读目录 安装 xlrd模块使用 xlwt模块 xlrd模块实现对excel文件内容读取,xlwt模块实现对excel文件的写入. 回到顶部 安装 ? ...
- 圆形进度条的模仿3-DrawArc,DrawCircle,DrawText,自定义属性实例讲解
前面两篇中已经讲过如何使用drawARC,等,画其他的图形的方法的使用也是一样的,只是参数不同, 同时也讲了如何通过xml进行自定义属性,接下来这篇便是通过实例讲解如何实地应用起来, 效果如下,点击开 ...
- C++学习笔记---数据类型
1.整型 C++中能够表示整型的类型有几下几种方式,区别在于所占内存空间不足 数据类型 占用空间 取值范围 short(短整型) 2字节 (-2^15~2^15-1) int(整型) 4字节 (-2^ ...
- C#文件序列化
前言 最近,为了实现Unity游戏数据的加密,我都把注意力放到了C#的加密方式身上,最简单的莫过于C#的序列化了,废话不多说,直接开始 准备工作 在使用文件序列化前我们得先引用命名空间 using S ...