在过去的几年工作中,曾经多次需要把文件上传到单独的服务器,而程序是在单独的服务器上部署的,在进行文件操作的时候就需要跨服务器进行操作包括:文件上传、文件下载、文件删除等。跨服务器文件操作一般是需要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跨服务器文件操作的更多相关文章

  1. 前后端分离跨服务器文件上传-Java SpringMVC版

    近来工作上不上特别忙,加上对后台java了解一点,所以就抽时间,写了一个java版本的前后端分离的跨服务器文件上传功能,包括前后端代码. 一.Tomcat服务器部分 1.Tomcat服务器 单独复制一 ...

  2. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  3. ABAP服务器文件操作

    转自http://blog.itpub.net/547380/viewspace-876667/ 在程序设计开发过程中,很多要对文件进行操作,这又分为对本地文件操作和服务器文件操作.对本地文件操作使用 ...

  4. java使用ftp上传文件

    ftpServer是apache MINA项目的一个子项目,它实现了一个ftp服务器,与vsftpd是同类产品.Filezilla是一个可视化的ftp服务器. ftp客户端也有很多,如Filezill ...

  5. JAVA调用FTP上传文件

    import java.io.File; import java.io.FileInputStream; import org.apache.commons.net.ftp.FTP; import o ...

  6. Java序列化与反序列化,文件操作

    参考两篇博客: http://blog.csdn.net/moreevan/article/details/6697777 http://blog.csdn.net/moreevan/article/ ...

  7. 通过ftp同步服务器文件:遍历文件夹所有文件(含子文件夹、进度条);简单http同步服务器文件实例

    该代码主要实现,指定ftp服务地址,遍历下载该地址下所有文件(含子文件夹下文件),并提供进度条显示:另外附带有通过http地址方式获取服务器文件的简单实例 废话不多说,直接上代码: 1.FTPHelp ...

  8. Java 之 File类(文件操作)

    一.概述 java.io.File 类是文件和目录路径名册抽象表示,主要用于文件和目录的创建.查找和删除等操作. File类是一个与系统无关的类,任何的操作系统都可以使用这个类中的方法. 路径问题: ...

  9. 跨服务器sql操作

    1.打开跨服务器功能 exec sp_configure 'show advanced options',1 reconfigure exec sp_configure 'Ad Hoc Distrib ...

随机推荐

  1. vue去掉地址栏#号

    mode:'history' 将这代码放入router.js里面

  2. Flink深入浅出: 资源管理(v1.11)

    -- 图片来自 <国家地理中文网>-- 往期推荐: Flink深入浅出:部署模式 Flink深入浅出:内存模型 Flink深入浅出:JDBC Source从理论到实战 Flink深入浅出: ...

  3. Kafka单机安装

    一.Kafka简介 Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写.Kafka是一种高吞吐量的 分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作 ...

  4. 微信小程序实时将less编译为wxss

    1.npm或者yarn全局安装wxss-cli npm install -g wxss-cli 2.运行waxes-cli命令(mp_wx为小程序目录) wxss ./mp_wx 实时监听mp_wx目 ...

  5. oracle 11g linux 导入中文字符乱码问题解决

    1. 涉及的字符集 这个可以分成三块,数据库服务器字符集(server).实例字符集(instance), 会话字符集(session) 2. 乱码的原因 session 的字符集和 server 的 ...

  6. 性能测试-CPU瓶颈分析的思路

    CPU(中央处理器),是电子计算机的主要设备之一,电脑中的核心配件.CPU作为计算机系统的运算和控制核心,是信息处理.程序运行的最终执行单元.CPU的功效主要为处理指令.执行操作.控制时间.处理数据. ...

  7. Helium文档7-WebUI自动化-highlight高亮显示元素

    前言 highlight方法是通过红框高亮显示元素,在调试中有很大优势,可以清楚看到定位的元素位置 入参介绍 def highlight(element):   """ ...

  8. C# 使用MySQL事务的使用方法

    //使用事务来处理多条数据,如果不成功则回滚 public void getCheckListSubmit() { string _conStr = "................&qu ...

  9. Markdown--补充版

    markdown语法实例 markdown语法实例 强调 分割线 引用 标题Setext方式 大标题 小标题 标题Atx方式 一级标题 二级标题 三级标题 四级标题 五级标题 六级标题 无序列表 有序 ...

  10. Zotero导入Markdown here插件

    1. 下载Markdown Here源码包 网址:https://github.com/adam-p/markdown-here 2. 创建.xpi后缀文件 将文件夹 中的这几个文件放入同一个文件夹中 ...