前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。
源代码大部分是网上找的,查来查去,找到几个可以用的例子,改来改去,揉合成现在这个样子。
一、 jar包准备(web service 的jar 不需要)
二、配置文件:
配置文件内容:
ftpUserName=hn_name
ftpPassword=hn_pwd
ftpHost=10.3.4.222
ftpPort=21
ftpPath=/home/hn_dhmp
writeTempFielPath=D\:\\ftpDownLoad
三、 ftp 工具类:
<strong>package ftp;import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;/*** ftp 上传、下载工具类* @author JiangYu*/
public class FtpUtil { private static Logger logger = Logger.getLogger(FtpUtil.class); /** * 获取FTPClient对象 * @param ftpHost FTP主机服务器 * @param ftpPassword FTP 登录密码 * @param ftpUserName FTP登录用户名 * @param ftpPort FTP端口 默认为21 * @return */ public static FTPClient getFTPClient(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort) { FTPClient ftpClient = null; try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器 ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { logger.info("未连接到FTP,用户名或密码错误 !"); ftpClient.disconnect(); } else { logger.info("FTP连接成功。"); } } catch (SocketException e) { e.printStackTrace(); logger.info("请检查FTP的IP地址 ! "); } catch (IOException e) { e.printStackTrace(); logger.info("请核对FTP的端口 ! "); } return ftpClient; } /*** 上传本地文件到FTP服务器 * @param ftpPath 服务器上存放文件的路径* @param ftpUserName ftp服务账号* @param ftpPassword ftp服务密码* @param ftpHost ftp服务ip* @param ftpPort ftp服务端口* @param fileContent 文件内容* @param writeTempFielPath 文件在本地的路径*/public static String upload(String ftpPath, String ftpUserName, String ftpPassword, String ftpHost, int ftpPort, String fileContent, String writeTempFielPath) { FTPClient ftpClient = null; String uploadResult = "";try { ftpClient = getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort); // 设置PassiveMode传输 ftpClient.enterLocalPassiveMode(); // 设置以二进制流的方式传输 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 对远程目录的处理 String remoteFileName = ftpPath; if (ftpPath.contains("/")) { remoteFileName = ftpPath .substring(ftpPath.lastIndexOf("/") + 1); } // 先把文件写出到本地,再上传到FTP上,最后再删除 。String result = write(remoteFileName, fileContent, writeTempFielPath); if (result.contains("成功")) { File f = new File(writeTempFielPath + "/" + remoteFileName); InputStream in = new FileInputStream(f); ftpClient.storeFile(remoteFileName, in); in.close(); uploadResult = "文件" + remoteFileName + "上传成功!";f.delete(); // 删除本地临时文件} else { uploadResult = "文件" + remoteFileName + "上传失败!";} return uploadResult;} catch (Exception e) { e.printStackTrace(); return uploadResult+"错误源: "+e.getMessage();}finally{ try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } /*** 文件写出到本地* @param fileName 文件名* @param fileContext 文件内容* @param writeTempFielPath 本地存储路径* @return*/public static String write(String fileName, String fileContext, String writeTempFielPath) { String result = "写出成功 !";try { File f = new File(writeTempFielPath + "/" + fileName); if(!f.exists()){ if(!f.createNewFile()){ result = "文件不存在,创建失败 !";} } BufferedWriter bw = new BufferedWriter(new FileWriter(f, true)); bw.write(fileContext.replaceAll("\n", "\r\n")); bw.flush(); bw.close(); return result; } catch (Exception e) { result = "写出失败 !";e.printStackTrace(); return result; } } /** * 从FTP服务器下载文件 * @param ftpHost FTP服务器IP * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName 要下载的文件名 * @param localPath 下载后保存到本地的路径 * @return */public static String downFile(String ftpHost, int port,String username, String password,String remotePath,String fileName,String localPath) { String result = "下载失败 !"; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(ftpHost, port); ftp.login(username, password); // 登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return "服务连接失败 !"; } ftp.changeWorkingDirectory(remotePath); // 转移到FTP服务器目录 FTPFile[] fs = ftp.listFiles(); boolean flag = false; // 下载文件不存在for(FTPFile ff:fs){ if(ff.getName().equals(fileName)){ File localFile = new File(localPath+"/"+ff.getName()); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), is); is.close(); flag = true;} }ftp.logout(); if(!flag){result = "文件: "+fileName+"不存在 !"; }else{result = "下载成功 !"; }} catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) {} } } return result; }} </strong>
upload方法可以用这个方法代替,直接上传整个文件,而不作用把文件内容作为参数,此方法主体代码来自网络:
package ftp;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import org.apache.commons.net.ftp.FTPClient;
/*** 文件上传替换方法 **/
public class FtpUpToo {private static FTPClient ftpClient = null; /** * ftp上传文件* @param targetFname 生成目标文件 * @return true||false */ public static boolean uploadFile(String targetFname){ int ftpPort = 0; String ftpUserName = ""; // ftp服务账号String ftpPassword = ""; // ftp服务密码String ftpHost = ""; // ftp服务ipString ftpPath = ""; // ftp服务器上存放文件的路径String writeTempFielPath = ""; // 文件在本地的路径String proName = "ftp.properties"; // 配置文件名try {// 配置文件一定要和本类放在同一包下才能找到 InputStream in = FtpUtil.class.getClassLoader().getResourceAsStream(proName); if (in == null) { throw new Exception("配置文件"+proName+"读取失败 !");} Properties properties = new Properties(); properties.load(in); ftpUserName = properties.getProperty("ftpUserName"); ftpPassword = properties.getProperty("ftpPassword"); ftpHost = properties.getProperty("ftpHost"); ftpPort = Integer.valueOf(properties.getProperty("ftpPort")) .intValue(); ftpPath = properties.getProperty("ftpPath"); writeTempFielPath = properties.getProperty("writeTempFielPath"); } catch (Exception e) {e.printStackTrace();} boolean flag = false; ftpClient = FtpUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort); if( ftpClient!=null ){ File srcFile = new File(writeTempFielPath+"/JiangYuUp.csv"); FileInputStream fis = null; try { fis = new FileInputStream(srcFile); //设置上传目录 ftpClient.changeWorkingDirectory(ftpPath); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); //设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //上传 flag = ftpClient.storeFile(targetFname, fis); } catch (Exception e) { e.printStackTrace(); closeCon(); }finally{ try {fis.close();System.out.println("运行结束!----");} catch (IOException e) {e.printStackTrace();}} } return flag; }/** * 销毁ftp连接*/ public static void closeCon(){ if(ftpClient !=null){ if(ftpClient.isConnected()){ try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } }
四、测试类:
<strong>package ftp;import java.io.InputStream;
import java.util.Properties;public class FtpTest { public static void main(String[] args) { new FtpTest().test();} private void test(){int ftpPort = 0; String ftpUserName = ""; // ftp服务账号String ftpPassword = ""; // ftp服务密码String ftpHost = ""; // ftp服务ipString ftpPath = ""; // ftp服务器上存放文件的路径String writeTempFielPath = ""; // 文件在本地的路径String proName = "ftp.properties"; // 配置文件名try { // 配置文件一定要和本类放在同一包下才能找到 InputStream in = FtpUtil.class.getClassLoader().getResourceAsStream(proName); if (in == null) { throw new Exception("配置文件"+proName+"读取失败 !");} Properties properties = new Properties(); properties.load(in); ftpUserName = properties.getProperty("ftpUserName"); ftpPassword = properties.getProperty("ftpPassword"); ftpHost = properties.getProperty("ftpHost"); ftpPort = Integer.valueOf(properties.getProperty("ftpPort")) .intValue(); ftpPath = properties.getProperty("ftpPath"); writeTempFielPath = properties.getProperty("writeTempFielPath"); // 下载String result = FtpUtil.downFile(ftpHost, ftpPort, ftpUserName, ftpPassword,ftpPath, "JiangYu.csv", writeTempFielPath); // JiangYu.csv:下载文件的名称System.out.println("文件下载结果为:" + result); // 上传ftpPath = ftpPath + "/" + "JiangYu.csv"; // JiangYu.csv:上传文件的名称FtpUtil.upload(ftpPath, ftpUserName, ftpPassword, ftpHost, ftpPort, "这里是文件内容", writeTempFielPath); } catch (Exception e) { e.printStackTrace(); } }
} </strong>
注: 测试类运行后下载成功的文件 和 上传时的临时文件是一样的名字,会被上传成功后删除临时文件操作所删除。
建议上传和下载分开测试。
五、 上传、下载结果: