ftp上传与下载
package com.demo.ftp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; /** * help:http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html * @author * */ public class FtpUtils { private FTPClient ftpClient; private boolean connectServer(String path,String url,int port,String username,String password){ boolean result = false; ftpClient = new FTPClient(); int reply ; try { //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftpClient.connect(url, port); // 下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件 ftpClient.setControlEncoding("UTF-8"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); //登录ftp ftpClient.login(username, password); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 看返回的值是不是230,如果是,表示登陆成功 reply = ftpClient.getReplyCode(); // 以2开头的返回值就会为真 if(!FTPReply.isPositiveCompletion(reply)){ ftpClient.disconnect(); System.out.println(">>>>>>>>>>>>>>>>连接服务器失败!"); result = false; }else{ ftpClient.changeWorkingDirectory(path); result = true; } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } private void uploadFile(File file){ if(file.isDirectory()){ try { ftpClient.makeDirectory(file.getName()); ftpClient.changeWorkingDirectory(file.getName()); String[] files = file.list(); for (int i = 0; i < files.length; i++) { File file1 = new File(file.getPath() + "\\" + files[i]); if (file1.isDirectory()) { uploadFile(file1); ftpClient.changeToParentDirectory(); } else { File file2 = new File(file.getPath() + "\\" + files[i]); FileInputStream input = new FileInputStream(file2); ftpClient.storeFile(file2.getName(), input); input.close(); } } } catch (IOException e) { e.printStackTrace(); } }else{ File file2 = new File(file.getPath()); FileInputStream input; try { input = new FileInputStream(file2); ftpClient.storeFile(file2.getName(), input); input.close(); } catch (Exception e) { e.printStackTrace(); } } } //下载 public void downLoad(String ftpFile, String dstFile) throws IOException { File file = new File(dstFile); FileOutputStream fos = new FileOutputStream(file); ftpClient.retrieveFile(ftpFile, fos); fos.close(); } public static void main(String[] args) throws Exception { FtpUtils t = new FtpUtils(); t.connectServer("", "测试ip", 21, "用户名", "密码"); File file = new File("F:\\test\\file\\file.txt"); // t.uploadFile(file); t.downLoad("file.txt", "F:\\test\\file\\file5.txt"); } }
成功根本没有什么秘诀可言,如果真是有的话,就是两个:第一个就是坚持到底,永不放弃;第二个是当你想放弃的时候,回过头来看看第一个秘诀:坚持到底,永不放弃