ftp上传,下载,删除文件

2023-05-16

ftp上传,下载,删除文件

直接看最下面的main()方法中的代码,复制全部代码,输入自己的ftp路径和用户信息。

package com.sinosoft.lis.ybt.bl;

import ind.crf.free.ftp.FTP;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.sinosoft.utility.CError;

public class TestFtp {

	public FTPClient ftpClient =  null;

	public FTP ftp = null;

	private String Host = null; // ftp 主机Host

	private String UserName = null;

	private  String Password = null;

	private  int Port = 21;

	public TestFtp()
	{
		System.out.println("begin");
	}

	/**
	 * 初始化
	 * @param ip FTP服务器地址
	 * @param user 服务名
	 * @param password 密码
	 * @param port 端口号
	 */
	public TestFtp(String host,String username,String password,int port)
	{
		this.Host= host;
		this.UserName= username;
		this.Password=password;
		this.Port= port;
	}


	/**
	 *  创建FTP连接 
	 */
	public boolean connectServer() {
		boolean flag = true;
		ftpClient = new FTPClient();
		int reply;
		try {
			ftpClient.connect(Host);
			ftpClient.login(UserName, Password);
			System.out.print(ftpClient.getReplyString());
			reply = ftpClient.getReplyCode();
//			 将文件传输类型设置为二进制
			System.out.println("FTPClient.ASCII_FILE_TYPE:"+FTPClient.ASCII_FILE_TYPE);
		    ftpClient.setFileTransferMode(FTPClient.ASCII_FILE_TYPE);
		    System.out.println("END:ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE)");
		    //防止server超时断开
			ftpClient.setDataTimeout(120000);
			if (!FTPReply.isPositiveCompletion(reply)){
				ftpClient.disconnect();
				System.out.println("FALSE:       FTPReply.isPositiveCompletion(reply)");
				System.err.println("FTP server refused connection.");
				flag = false;
			}
			System.out.println("END:      connectServer()");
		}catch (SocketException e){
			flag = false;
			e.printStackTrace();
			System.err.println("登录ftp服务器 " + Host + " 失败,连接超时!");

		}catch (IOException e){
			flag = false;
			e.printStackTrace();
			System.err.println("登录ftp服务器 " + Host + " 失败,FTP服务器无法打开!");
		}catch(Exception e){
			flag = false;
			e.printStackTrace();
			System.err.println("登录ftp服务器 " + Host + " 失败,原因未知!");
		}

		System.out.println("登陆ftp服务器成功"+Host);
		return flag;
	}

	/**
	 * 关闭连接
	 */
	private  void closeConnect() {
		try {
			if (ftpClient != null) {

				ftpClient.disconnect();
			}
            //ftpClient = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 删除ftp上的文件 
	 * @param srcFname 相对路径
	 * @return
	 */
	 public int removeFile(String srcFname){  
	        int flag = 0;  
	        if( ftpClient!=null ){  
	            try {  
	                flag = ftpClient.dele(srcFname);
	                System.out.println("removeFile()返回值:"+flag);//测试删除成功返回250,失败返回550
	            } catch (IOException e) { 
	            	flag = 0;
	                e.printStackTrace();  
	                this.closeConnect();  
	            }  
	        }  
	        return flag;  
	    }
	  
	 /**
	  * 删除ftp上的空文件夹 
	  * @param srcFname 相对路径
	  * @return
	  */
	 public boolean deleteDirectory(String srcFname){  
	        boolean flag = true;  
	        if( ftpClient!=null ){  
	            try {  
	            	flag= ftpClient.removeDirectory(srcFname);
	            	System.out.println("removeDirectory() 返回值:"+flag);
	            } catch (IOException e) { 
	            	flag = false;
	                e.printStackTrace();  
	                this.closeConnect();  
	            }  
	        }
	        return flag;
	          
	    }
	 /**
	  * 重命名ftp上的文件
	  * @param oldFileName 旧名字
	  * @param newFileName 新旧名字
	  * @return
	  */
	 public  boolean renameFile(String oldFileName,String newFileName) {  
	   	boolean flag = true;
	      try {
	    	  flag = ftpClient.rename(oldFileName, newFileName);  
	    	  System.out.println("重命名!!"+flag);

	      } catch (Exception e) {  
	          e.printStackTrace();  
	      }  
	      return flag;
	  }  
	 
	 /**
	  * ftp上的创建文件夹
	  * @param dirname 名字
	  * @return
	  */
	    public boolean createDir(String dirname){
	    	boolean flag = true;
	    	  try{
	        	  flag = ftpClient.makeDirectory(dirname);
	    	      System.out.println(flag+"  在目标服务器上成功建立了文件夹: " + dirname);
	    	  }catch(Exception ex){
	    	    System.out.println(ex.getMessage());
	    	  }
	    	  return flag;
	    	}

	
	/**
	 * 参数说明:
	 * localStr:本地目录+文件名,都用绝对路径
	 * remoteStr = 远程目录+文件名,如果要取的文件直接在登陆后的默认目录下,这里远程目录可以不要 remoteStr = /文件名;
	 */
	public boolean ApacheFTPDownFile(String localStr, String remoteStr)
	{
		try {
			FileOutputStream fos = null;
			Calendar cCalendar = Calendar.getInstance();
			long currTime = cCalendar.getTimeInMillis();

			if(connectServer()){
				/*得到相应的目录和远程文件*/
				int i =0;
			//	i = remoteStr.lastIndexOf(File.separator);
				i = remoteStr.lastIndexOf("/");
				String   currDir = remoteStr.substring(0, i);
				String   Remotefile = remoteStr.substring(i + 1);

				if (remoteStr.equals("")) {
					System.out.println("请输入正确的文件名!");
					return false;
				}
				if(!checkRemoteFile(currDir,Remotefile)){
					return false;
				}
				// 若本地路径不存在则生成路径
				if(!checkLocalDir(localStr)){
					return false;
				}
				//下载文件到本地
				File file = null;
				file = new File(localStr);
				fos = new FileOutputStream(file);
				ftpClient.retrieveFile(Remotefile, fos);
				System.out.println(ftpClient.getReplyString());
				fos.flush();
				fos.close();
				closeConnect();

				cCalendar = Calendar.getInstance();
				long currTime2 = cCalendar.getTimeInMillis();
				long diff2 = currTime2 - currTime;
				System.out.println("所用时间为=" + diff2);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("下载文件失败!!!!");
			return false; 
		}
		return true;

	}


	private boolean checkLocalDir(String localStr )
	{
        System.out.println("!!!!!:"+localStr);
		File formatPath = null;
		//int j = localStr.lastIndexOf("\\");
		int j = localStr.lastIndexOf("//");
		String localDir = localStr.substring(0, j);
		formatPath = new File(localDir);
		if (!formatPath.exists()) {
			formatPath.mkdirs();
		}
		// TODO Auto-generated method stub
		return true;
	}
	
	private boolean checkLocalDir1(String localStr )
	{

		File formatPath = null;
		int j = localStr.lastIndexOf("/");
		String localDir = localStr.substring(0, j);
		formatPath = new File(localDir);
		if (!formatPath.exists()) {
			formatPath.mkdirs();
		}
		// TODO Auto-generated method stub
		return true;
	}


	/*
	 * 对远程文件进行分析
	 * */
	private boolean checkRemoteFile(String cFileDir,String cFileName)
	{
		try{
			boolean tFlag = false;
			System.out.println("1111111:"+cFileDir);
			System.out.println("2222222:"+cFileName);

			tFlag = ftpClient.changeWorkingDirectory(cFileDir);
			if (!tFlag) {
				System.out.println("路径出错");	
				CError tError = new CError();
				tError.moduleName = "ApacheFTP";
				tError.functionName = "dealData";
				tError.errorMessage = "请检查:[" + cFileDir + "]路径是否正确";
				return false;
			}

			System.out.println(ftpClient.printWorkingDirectory());
			System.out.println(ftpClient.getReplyString());

			FTPFile ff[] = ftpClient.listFiles();
			boolean fileExist = false;
			if (ff == null || ff.length == 0) {
				System.out.println("该目录下无任何文件!");
				return false;
			} else {
				System.out.println("该目录下有文件!length:"+ff.length);
				for(int j = 0;j<ff.length;j++){
					if(ff[j].getName().equals(cFileName)){
						System.out.println("在FTP目录上找到了文件!");
						fileExist = true;
						break;           			
					}            		
				}
			}
			if(!fileExist){

				System.out.println("在FTP目录下没有读取到文件");
				return false;                        	
			}
			return true;      
		}
		catch (Exception ex) {
			ex.printStackTrace();
			try {
				if (ftpClient != null) {
					ftpClient.disconnect();
				}
			} catch (Exception e) {
			}
			return false;
		}

	}


	/**
	 * 获取文件
	 * 
	 * @param localStr
	 *            本地文件全路径名
	 * @param remoteStr
	 *            远程文件全路径名
	 */
	public boolean FTPGetFile(String localStr, String remoteStr, String address,
			String user, String pass) 
	{
		Host = address;
		UserName = user;
		Password = pass;
		Port = 21;

		if (!ftpLogin()) {
			System.out.println("FTP登陆失败,Host:" + Host + " Port:" + Port
					+ " UserName:" + UserName + " Password:" + Password);
			return false;
		}
		System.out.println("下载文件:" + localStr + "," + remoteStr);
		String Remotefile = "";
		String currDir = "";
		int i = 0;
		ftp.setTransfer(FTP.TRANSFER_PASV);
		ftp.setMode(FTP.MODE_AUTO);
		/* 对远程文件进行分析 */
		if (remoteStr.equals("")) {
			System.out.println("请输入正确的文件名!");
			return false;
		}
		/* 得到相应的目录和远程文件 */
		i = remoteStr.lastIndexOf("/");
		currDir = remoteStr.substring(0, i);
		Remotefile = remoteStr.substring(i + 1);
		System.out.println("CurrDir is  :" + currDir);
		System.out.println("FileName is :" + Remotefile);
		ftp.cd(currDir);
		System.out.print(ftp.lastReply());
		System.out.println("FTP.CODE_TRANSFER_OK:" + FTP.CODE_TRANSFER_OK);
		System.out.println("ftp.lastCode()111:" + ftp.lastCode());
		if (ftp.lastCode() != FTP.CODE_CD_OK) {
			System.out.println("the remote directory does not exist.");
			ftp.disconnect();
			return false;
		}
		/**
		 * 没有路径生成路径
		 */
	//	int j = localStr.lastIndexOf("\\");
		int j = localStr.lastIndexOf("//");
		String localDir = localStr.substring(0, j);
		File file = new File(localDir);
		if (!file.exists()) {
			System.out.println("the local directory does not exist.");
			file.mkdirs();
		}
		System.out.println("ftp.lastCode()222:" + ftp.lastCode());
		ftp.download(Remotefile, localStr);
		System.out.println(ftp.lastReply());
		System.out.println("ftp.lastCode()333:" + ftp.lastCode());
		if (ftp.lastCode() != FTP.CODE_TRANSFER_OK) {
			System.out.println("error while downloading");
			ftp.disconnect();
			File f = new File(localStr);
			long taille = f.length();
			System.out.println("taille:::"+taille);
			ftpLogin();
			ftp.cd(currDir);
			long rollback = 512;
			ftp.download(Remotefile, localStr, taille - rollback);
		}
		ftp.disconnect();

		return true;
	}

	public boolean ftpLogin() 
	{
		ftp = new FTP(Host, Port);
		ftp.connect();
		System.out.print(ftp.lastReply());
		if (ftp.lastCode() != FTP.CODE_CONNECT_OK) {
			System.out.println("Connection failed.");
			return false;
		}
		ftp.login(UserName, Password);
		System.out.print(ftp.lastReply());
		if (ftp.lastCode() != FTP.CODE_LOGGEDIN) {
			ftp.disconnect();
			return false;
		}
		return true;
	}
	public void upFile(String path, String filename, String localFilePath)
	{
		try {
			this.connectServer();
			FileInputStream in=new FileInputStream(new File(localFilePath));
			ftpClient.changeWorkingDirectory(path);
			ftpClient.storeFile(filename, in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}  

	}

	/**
	 * 上传文件
	 * @param file 文件
	 * @param path 上传服务器路径
	 * @return
	 */
	public boolean ApacheFTPUploadFile(File file,String path){
		try
		{
			if (!file.isFile()) {
				//不是文件
				return false;
			}else if(!fileSize(file)){
				//控制文件大小
				return false;
			}

			if (!connectServer()) {
				return false;
			}
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			//转到path路径
			//path=this.pathAddress(path);

			ftpClient.makeDirectory(path);

			//进入服务器目录
			if(!ftpClient.changeWorkingDirectory(path)){
				System.out.println("上载路径出错");
				return false;
			}

			//给文件加上时间撮,防止服务器文件重复
			String fileName=file.getName();
			/*
			 * sl add 2008年12月27日22:53:25
			 * 加上时间撮是合理的,但邮储要求文件格式必须要满足他们的要求
			 * 可以跟他们沟通让他们的格式要求中增加时间撮,我们的程序就不主动给它添加时间撮了
			 * 这里先注掉它!
			 */
//			int lastIndex=fileName.lastIndexOf(".");
//			fileName=fileName.substring(0,lastIndex)+"_"+System.currentTimeMillis()+fileName.substring(lastIndex);
			FileInputStream fis=null;
			try {
				fis=new FileInputStream(file);
				if(!ftpClient.storeFile(fileName, fis)){
					closeConnect();
					return false;
				}
//                closeConnect();
//                fis.close();
//                String strOldName = file.getPath();
//                String strNewName ="";
//                if(file.getName().indexOf(".des")>=0)
//                {
//                    strNewName = strOldName.substring(0, strOldName.length() - 8)
//                    + ".dat";
//                }
//                else
//                {
//                    strNewName = strOldName.substring(0, strOldName.length() - 4)
//                    + ".dat";
//                }
//                File fileNew = new File(strNewName);
//
//                if (fileNew.exists()) {
//                    fileNew.delete();
//                }
//                //file.
//                if (!file.renameTo(fileNew)) {
//                    return false;
//                }
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}finally{
				if (fis != null) {
					fis.close();
				}
				closeConnect();
			}

		}
		catch(IOException e){
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	
	
	/**
	 * 控制文件的大小,默认为5M
	 * @param file_in 文件
	 */
	private boolean fileSize(File file_in) {

		return this.fileSize(file_in,5);
	}

	/**
	 * 控制文件的大小
	 * @param file_in 文件
	 * @param size 文件大小,单位为M
	 */
	private boolean fileSize(File file_in,int size) {
		if (file_in == null || file_in.length() == 0) {
			//文件为空
			return false;
		} else {
			if (file_in.length() > (1024 * 1024 * size)){
				//文件大小不能大与size
				return false;
			}
		}
		return true;
	}
	/**
	 * 格式化文件路径 检查path最后有没有分隔符'\'
	 * @param path
	 * @return
	 */
	public String pathAddress(String path){

		if (path==null || path.length()<1) {
			return "";
		}
		String temp_path=path.substring(path.length()-1);
		if (!temp_path.equals("/") && !temp_path.equals("\\")) {
			temp_path=path+File.separator;
		}else{
			temp_path=path;
		}
		return temp_path;

	}

	//add by 
	public boolean getAndUpFile(String downLoadFileName,String upLoadFileName){
		String path = "\\bea\\ui\\temp\\pabcvideocache\\";
		
		File exeFile1 = new File(path);
		if(!exeFile1.exists()){
				boolean bo = exeFile1.mkdir();
				System.out.println(bo+"创建文件夹"+exeFile1);
		}
		String cache_filePath = path+upLoadFileName.substring(upLoadFileName.lastIndexOf("/")+1);
		System.out.println("getAndUpFile:\t"+cache_filePath);
		FTPGetFile(cache_filePath,downLoadFileName,Host,UserName,Password);
		
		upFile(upLoadFileName.substring(0,upLoadFileName.lastIndexOf("/")),upLoadFileName.substring(upLoadFileName.lastIndexOf("/")+1),cache_filePath);
		
		File file = new File(cache_filePath);
		file.delete();
		return true;
	}
	
	public  String getHost() {
		return Host;
	}
	public  void setHost(String cHost) {
		Host = cHost;
	}
	public  String getUser() {
		return UserName;
	}
	public  void setUser(String user) {
		UserName = user;
	}
	public  String getPassword() {
		return Password;
	}
	public  void setPassword(String password) {
		Password = password;
	}
	public  int getPort() {
		return Port;
	}
	public  void setPort(int port) {
		Port = port;
	}

	
	
	public static void main(String[] args) {
		String ip="输入ftp地址";
		String user="输入用户名r";
		String password="输入密码";
		int port=21;
		
		TestFtp tTestFtp = new TestFtp(ip,user,password,port);
		File file = new File("E://001/上传文件.zip");
		
		//上传文件
		tTestFtp.ApacheFTPUploadFile(file, "/u01/fileZip/zip/bocFTP/");
		
		//下载文件  例如:/u01/fileZip/zip/bocFTP/3123213.txt
		tTestFtp.ApacheFTPDownFile("E://003/555.txt","输入ftp文件的路径带着要下载文件的名字");
		
		//另一个下载文件
		tTestFtp.FTPGetFile("E://003/ff.txt", "输入ftp文件的路径带着要下载文件的名字", "输入ftp地址", "输入用户名", "输入密码");
		
	
	}
	
}






本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ftp上传,下载,删除文件 的相关文章

  • 使用calibre制作带目录的mobi电子书

    1 把word等格式的书籍转换成txt格式的文件 xff0c 另外再重新把txt文件打开 xff0c 另存为UTF 8格式的文件 2 在想设为目录条目的地方输入 符号 xff0c 一级目录输入一个 xff0c 二级目录输入 3 在每段开头处
  • redis的快照和集群部署

    1 安装 使用redis 3 2 8 tar gz tar zxvf redis 3 2 8 tar gz cd redis 3 2 8 make amp amp make test amp amp make install xff08 1
  • 解决cannot open shared object file: No such file or directory

    一 linux下调用动态库 so文件时提示 xff1a cannot open shared object file No such file or directory 解决办法 xff1a 1 此时ldd xxx查看依赖缺少哪些库 lib
  • Activity的启动模式以及onNewIntent和onConfigurationChanged这两个生命周期方法的场景

    1 Activity的启动模式有哪几种 xff0c 分别用于什么场景 xff1f Activity的启动模式的4种 xff1a standard标准启动模式 xff0c 默认的启动模式 每一次启动这个activity都会创建新的activi
  • node 第三方模块系列------minimist轻量级的命令行参数解析引擎

    总体介绍 xff1a node js的命令行参数解析工具有很多 xff0c 比如 xff1a argparse optimist yars commander optimist和yargs内部使用的解析引擎正是minimist xff0c
  • Python教程:文件路径/目录获取教程

    一 获取文件路径实现 1 获取当前文件路径 span class token keyword import span os current file path span class token operator 61 span file s
  • npm的安装及缓存机制详解

    npm的安装机制 下面我们会通过一个流程图来具体学习npm install的安装机制 npm install执行之后 首先会检查和获取 npm的配置 这里的优先级为 项目级的 npmrc文件 gt 用户级的 npmrc文件 gt 全局级的
  • s7epaapidll丢失怎么办_s7epaapidll下载

    s7epaapi dll找不到怎么修复 xff1f 很多用户玩单机游戏或者安装软件的时候就出现过这种问题 xff0c 如果是新手第一时间会认为是软件或游戏出错了 xff0c 其实并不是这样 xff0c 其主要原因就是你电脑的该dll文件没有
  • 01-Elasticsearch安装与配置

    一 Elasticsearch 介绍 Elasticsearch是一个实时分布式搜索和分析引擎 二 运行环境 系统 Centos 7JDK 1 8ES版本 7 5 1 下载地址 https www elastic co cn downloa
  • 01-Liunx_用户操作

    一 创建用户组 创建用户组 root 64 localhost bin groupadd 用户组名称 example groupadd test 删除用户组 root 64 localhost bin groupdel 用户组名称 exam
  • 打工与乘公交

    去一个公司打工就如同上了一辆公交车 在上车之前 xff0c 你应该清楚自己打算去哪里 xff0c 打算在哪里下车 有的公交车很豪华 xff0c 有的很破烂 xff0c 但是这并不是重点 xff0c 所有能开到目的地的车都是好车 上了车之后
  • 01-MyBatis Plus-配置信息

    一 官网 URL https mp baomidou com 二 特性 无侵入 xff1a 只做增强不做改变 xff0c 引入它不会对现有工程产生影响 xff0c 如丝般顺滑损耗小 xff1a 启动即会自动注入基本 CURD xff0c 性
  • 五分钟教你手写HashMap

    原作者 xff1a 老铁123 出处 xff1a https blog csdn net qewgd article details 85927183 本文归作者 老铁123 和博客园共有 xff0c 欢迎转载 xff0c 但未经作者同意必
  • Java实现快速排序算法

    原作者 xff1a 老铁123 出处 xff1a https blog csdn net qewgd article details 85949755 本文归作者 老铁123 和博客园共有 xff0c 欢迎转载 xff0c 但未经作者同意必
  • 手写ArrayBlockingQueue

    个人分类 xff1a 算法 编辑 原作者 xff1a 老铁123 出处 xff1a https blog csdn net qewgd article details 88363745 本文归作者 老铁123 和博客园共有 xff0c 欢迎
  • 手写LinkedBlockingQueue

    原作者 xff1a 老铁123 出处 xff1a https blog csdn net qewgd article details 88364742 本文归作者 老铁123 和博客园共有 xff0c 欢迎转载 xff0c 但未经作者同意必
  • Viewbinding自动生成XML的一个对应绑定类

    当你在项目 Module 的build gradle中的android 中设置 buildFeatures viewBinding true 设置完sync一下 xff0c 然后会在项目中看到对应的XML文件的一个继承了ViewBindin
  • AE制作Json动画教程

    本文将从为什么要做动画 xff0c 到动画实现方式 xff0c 再到用AE 43 Bodymovin制作动画 xff0c 结合实际案例行分享 xff0c 希望给新手带来一些启发 首先我们来聊聊 xff0c 我们为什么要做动效 xff1f 1
  • zabbix proxy 表分区

    zabbix server进行表分区的话 xff0c zabbix的内部管家会失效 xff0c 这个时候 xff0c 如果有proxy的话 xff0c 也要进行表分区 xff0c proxy表分区比较简单 xff0c 也不用每天更换分区 步
  • pycharm中unresolved reference怎么解决(配置问题)

    iunresolved reference怎么解决 解决方法 xff1a xff08 本人使用方法二解决的 xff09 方法1 进入PyCharm gt Settings gt Build Excution Deployment gt Co

随机推荐