杂记:java连接ftp服务器(解决中文乱码问题)

注:每次请求都是先登陆服务器的,代码中报错部分代码无用,先删除
ftp的用户信息可以写的配置文件中,该代码写在了redis中,请自行修改

package com.founder.zxb.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;

import com.founder.zxb.model.SysConfIg;
import com.founder.zxb.redis.service.CacheService;
import com.founder.zxb.services.impl.SysConfIgServiceImpl;

 
public class FtpUtil {
	
	/** 
	 * Description: 向FTP服务器上传文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param basePath FTP服务器基础目录
	 * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
	 * @param filename 上传到FTP服务器上的文件名 
	 * @param input 输入流 
	 * @return 成功返回true,否则返回false 
	 */  
	public static boolean uploadFile(String filePath, String filename, InputStream input) {
		boolean result = false;
		FTPClient ftp = loginFtp();
		if(ftp==null) {
			return false;
		}
		try {
			//切换到上传目录
			if (!ftp.changeWorkingDirectory("/"+filePath)) {
				//如果目录不存在创建目录
				String[] dirs = filePath.split("/");
				String tempPath = "/";
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) continue;
					tempPath += "/" + dir;
					if (!ftp.changeWorkingDirectory(tempPath)) {  //进不去目录,说明该目录不存在
						if (!ftp.makeDirectory(tempPath)) { //创建目录
							//如果创建文件目录失败,则返回
							System.out.println("创建文件目录"+tempPath+"失败");
							return result;
						} else {
							//目录存在,则直接进入该目录
							ftp.changeWorkingDirectory(tempPath);	
						}
					}
				}
			}
			//设置上传文件的类型为二进制类型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			
			//上传文件
			//if (!ftp.storeFile(new String(filename.getBytes("GBK"), "iso-8859-1"), input)) {GBK(gb2312)
			if (!ftp.storeFile(new String(filename.getBytes(), "iso-8859-1"), input)) {
				return result;
			}
			input.close();
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	/** 
	 * Description: 从FTP服务器下载文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param remotePath FTP服务器上的相对路径 
	 * @param fileName 要下载的文件名 
	 * @return 
	 */  
	public static boolean downloadFile(String remotePath,String fileName ,HttpServletResponse response) {
		boolean result = false;
		FTPClient ftp = loginFtp();
		if(ftp==null) {
			return false;
		}
		try {
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			ftp.enterLocalPassiveMode();
			FTPFile[] fs = ftp.listFiles(remotePath);
			for (FTPFile ff : fs) {
				if (ff.getName().equals(new String(fileName.getBytes(),"ISO8859-1"))) {
					InputStream fis = ftp.retrieveFileStream(ff.getName());
					response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"ISO8859-1"));
					response.setContentType("application/octet-stream");
					
					OutputStream out = response.getOutputStream();
		            byte[] b = new byte[2048];
		            int len;
		            while ((len = fis.read(b)) != -1) {
		                out.write(b, 0, len);
		            }
		            fis.close();
		            out.close();
		            result = true;
				}
			}
 
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		
		return result;
	}
	/**
	 * 下载文件返回文件流
	 * @param remotePath
	 * @param fileName
	 * @param response
	 * @return
	 */
	public static InputStream  downloadFile(String remotePath,String fileName) {
		FTPClient ftp = loginFtp();
		if(ftp==null) {
			return null;
		}
		try {
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(new String(fileName.getBytes(),"ISO8859-1"))) {
					InputStream fis = ftp.retrieveFileStream(ff.getName());
		            return fis;
				}
			}
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		
		return null;
	}
	
	/**
	 * 
	 * @param host
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @param response
	 * @return
	 */
	public static boolean deleteFile(String remotePath,String fileName ) {
		boolean result = false;
		FTPClient ftp = loginFtp();
		if(ftp==null) {
			return false;
		}
		try {
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			//删除文件
			ftp.dele(fileName); 
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		
		return result;
	}
 
	//ftp上传文件测试main函数
//	public static  void six() {
//		try {  
//	        FileInputStream in=new FileInputStream(new File("C:\\Users\\bai\\FtpSite\\123.txt"));  
//	        boolean flag = uploadFile("172.19.203.84", 21, "ftpuser", "admin", "/","/2017/11/19", "hello.txt", in);  
//	        System.out.println(flag);  
//	    } catch (FileNotFoundException e) {  
//	        e.printStackTrace();  
//	    }  
//	}
//	
	private static FTPClient loginFtp() {
		CacheService cacheService = (CacheService)SpringContextUtils.getBean(CacheService.class);
		SysConfIgServiceImpl sysConfIgServiceImpl = (SysConfIgServiceImpl)SpringContextUtils.getBean(SysConfIgServiceImpl.class);
		FTPClient ftp = new FTPClient();
		int reply;
		Map<String,String> map=cacheService.get("ftp_map");
		if(map==null) {
			map=new HashMap();
			List<SysConfIg> list=sysConfIgServiceImpl.findFtpByCode("ftp");
			for(SysConfIg sysConfIg:list) {
				map.put(sysConfIg.getName(), sysConfIg.getValue());
			}
			cacheService.set("ftp_map", map);
		}
		try {
			ftp.connect(map.get("host"), Integer.valueOf(map.get("port")));
			ftp.login(map.get("userName"), map.get("passWord"));// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
		
		return ftp;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用: C:\Windows\System32中cmd文件丢失,如果打开cmd,显示不存在,那么你的电脑里面的cmd.exe可执行文件丢失了,需要重新添加,打开我的电脑,搜索如下路径:C:\Windows\System32 ,将下载下来的cmd.exe文件添加到这个路径下。 引用: 设置快捷方式路径cmd.exe的文件路径是c:\windows\system32\cmd.exe。 根据你的描述,C:\Windows\System32\cmd.exe是cmd.exe的文件路径。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C:\Windows\System32 中 cmd丢失,cmd.exe 下载](https://download.csdn.net/download/weixin_40446557/10347662)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [根据cmd.exe的文件路径,30秒新建cmd快捷方式,并以管理员身份运行(保姆级图文)【杂记】](https://blog.csdn.net/u011027547/article/details/122837561)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [终端进程启动失败: shell 可执行文件“C:\Windows\System32\cmd.exe ”的路径不存在。](https://blog.csdn.net/irober/article/details/120679263)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值