Java操作ftpClient常用方法
- 格式:docx
- 大小:36.59 KB
- 文档页数:2
ftpclient storefile用法-回复标题:ftpclient storefile用法详解:一步一步回答导语:FTPClient是Java中常用的用于实现文件传输的类库之一。
其中的storeFile方法用于将本地文件上传至FTP服务器。
本文将从使用环境的准备、storeFile使用方法、相关注意事项等方面进行详尽解读,帮助读者深入了解并正确应用ftpclient storefile。
第一部分:使用环境的准备在开始使用storeFile方法之前,我们需要准备以下环境:1. Java开发环境:确保已经正确配置Java环境,并且能够运行Java程序。
2. FTP服务器:需要有可供连接和上传文件的FTP服务器,可以使用本地搭建的FTP服务器或者远程FTP服务器。
3. 相关类库:需要引入Apache Commons Net类库,其中包含了FTPClient类。
第二部分:storeFile方法的使用方法1. 创建FTPClient对象:首先,我们需要创建一个FTPClient对象。
可以使用以下代码进行实例化:FTPClient ftpClient = new FTPClient();2. 连接FTP服务器:使用ftpClient对象的connect方法连接FTP服务器。
例如,连接至本地FTP服务器的代码如下:ftpClient.connect("localhost");3. 登录FTP服务器:调用ftpClient对象的login方法进行登录。
通常需要提供用户名和密码。
示例代码如下:ftpClient.login("username", "password");4. 设置文件传输模式:通过调用ftpClient的setFileType方法,可以设置上传文件的传输模式。
有ASCII模式和二进制模式两种选择。
例如,设置为二进制模式的代码如下:ftpClient.setFileType(FTP.BINARY_FILE_TYPE);5. 指定本地文件和远程路径:使用storeFile方法之前,需要指定本地待上传文件的路径和名称,以及目标服务器上保存的文件名。
java实现ftp的几种方式(第3方包)最近在做ssh ,sftp。
顺便总结一下java实现ftp的几种方式。
.StringTokenizer;public class FtpUpfile {private FtpClient ftpclient;private String ipAddress;private int ipPort;private String userName;private String PassWord;/*** 构造函数* @param ip String 机器IP* @param port String 机器FTP端口号* @param username String FTP用户名* @param password String FTP密码* @throws Exception*/public FtpUpfile(String ip, int port, String username, String password) throws Exception {ipAddress = new String(ip);ipPort = port;ftpclient = new FtpClient(ipAddress, ipPort);//ftpclient = new FtpClient(ipAddress);userName = new String(username);PassWord = new String(password);}/*** 构造函数* @param ip String 机器IP,默认端口为21* @param username String FTP用户名* @param password String FTP密码* @throws Exception*/public FtpUpfile(String ip, String username, String password) throws Exception {ipAddress = new String(ip);ipPort = 21;ftpclient = new FtpClient(ipAddress, ipPort);//ftpclient = new FtpClient(ipAddress);userName = new String(username);PassWord = new String(password);}/*** 登录FTP服务器* @throws Exception*/public void login() throws Exception {ftpclient.login(userName, PassWord);}/*** 退出FTP服务器* @throws Exception*/public void logout() throws Exception {//用ftpclient.closeServer()断开FTP出错时用下更语句退出ftpclient.sendServer("QUIT\r\n");int reply = ftpclient.readServerResponse(); //取得服务器的返回信息}/*** 在FTP服务器上建立指定的目录,当目录已经存在的情下不会影响目录下的文件,这样用以判断FTP* 上传文件时保证目录的存在目录格式必须以"/"根目录开头* @param pathList String* @throws Exception*/public void adServerResponse();}ftpclient.binary();}/*** 取得指定目录下的所有文件名,不包括目录名称* 分析nameList得到的输入流中的数,得到指定目录下的所有文件名* @param fullPath String* @return ArrayList* @throws Exception*/public ArrayList fileNames(String fullPath) throws Exception {ftpclient.ascii(); //注意,使用字符模式TelnetInputStream list = List(fullPath);byte[] names = new byte[2048];int bufsize = 0;bufsize = list.read(names, 0, names.length); //从流中读取list.close();ArrayList namesList = new ArrayList();int i = 0;int j = 0;while (i < bufsize /*names.length*/) {//char bc = (char) names;//System.out.println(i + " " + bc + " : " + (int) names);//i = i + 1;if (names[i] == 10) { //字符模式为10,二进制模式为13//文件名在数据中开始下标为j,i-j为文件名的长度,文件名在数据中的结束下标为i -1//System.out.write(names, j, i - j);//System.out.println(j + " " + i + " " + (i - j));String tempName = new String(names, j, i - j);namesList.add(tempName);//System.out.println(temp);// 处理代码处//j = i + 2; //上一次位置二进制模式j = i + 1; //上一次位置字符模式}i = i + 1;}return namesList;}/*** 上传文件到FTP服务器,destination路径以FTP服务器的"/"开始,带文件名、* 上传文件只能使用二进制模式,当文件存在时再次上传则会覆盖* @param source String* @param destination String* @throws Exception*/public void upFile(String source, String destination) throws Exception { buildList(destination.substring(0, stIndexOf("/")));ftpclient.binary(); //此行代码必须放在buildList之后TelnetOutputStream ftpOut = ftpclient.put(destination);TelnetInputStream ftpIn = new TelnetInputStream(newFileInputStream(source), true);byte[] buf = new byte[204800];int bufsize = 0;while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {ftpOut.write(buf, 0, bufsize);}ftpIn.close();ftpOut.close();}ush();ftpOut.close();}/*** 从FTP文件服务器上下载文件SourceFileName,到本地destinationFileName * 所有的文件名中都要求包括完整的路径名在内* @param SourceFileName String* @param destinationFileName String* @throws Exception*/public void downFile(String SourceFileName, String destinationFileName) throws Exception {ftpclient.binary(); //一定要使用二进制模式TelnetInputStream ftpIn = ftpclient.get(SourceFileName);byte[] buf = new byte[204800];int bufsize = 0;FileOutputStream ftpOut = new FileOutputStream(destinationFileName);while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {ftpOut.write(buf, 0, bufsize);}ftpOut.close();ftpIn.close();}/***从FTP文件服务器上下载文件,输出到字节数组中* @param SourceFileName String* @return byte[]* @throws Exception*/public byte[] downFile(String SourceFileName) throwsException {ftpclient.binary(); //一定要使用二进制模式TelnetInputStream ftpIn = ftpclient.get(SourceFileName);ByteArrayOutputStream byteOut = new ByteArrayOutputStream();byte[] buf = new byte[204800];int bufsize = 0;while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {byteOut.write(buf, 0, bufsize);}byte[] return_arraybyte = byteOut.toByteArray();byteOut.close();ftpIn.close();return return_arraybyte;}/**调用示例* FtpUpfile fUp = new FtpUpfile("192.150.189.22", 21, "admin", "admin");* fUp.login();* fUp.buildList("/adfadsg/sfsdfd/cc");* String destination = "/test.zip";* fUp.upFile("C:\\Documents and Settings\\Administrator\\My Documents\\sample.zi p",destination);* ArrayList filename = fUp.fileNames("/");* for (int i = 0; i < filename.size(); i++) {* System.out.println(filename.get(i).toString());* }* fUp.logout();* @param args String[]* @throws Exception*/public static void main(String[] args) throws Exception {FtpUpfile fUp = new FtpUpfile("172.16.0.142", 22, "ivr", "ivr");fUp.login();/* fUp.buildList("/adfadsg/sfsdfd/cc");String destination = "/test/SetupDJ.rar";fUp.upFile("C:\\Documents and Settings\\Administrator\\My Documents\\SetupDJ.rar", destination);ArrayList filename = fUp.fileNames("/");for (int i = 0; i < filename.size(); i++) {System.out.println(filename.get(i).toString());}fUp.downFile("/sample.zip", "d:\\sample.zip");*/FileInputStream fin = new FileInputStream("d:\\wapPush.txt");byte[] data = new byte[20480000];fin.read(data, 0, data.length);fUp.upFile(data, "/home/cdr/wapPush.txt");fUp.logout();System.out.println("程序运行完成!");/*FTP远程命令列表USER PORT RETR ALLO DELE SITE XMKD CDUP FEATPASS PASV STOR REST CWD STAT RMD XCUP OPTSACCT TYPE APPE RNFR XCWD HELP XRMD STOU AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZQUIT MODE SYST ABOR NLST MKD XPWD MDTM PROT *//*在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\nftpclient.sendServer("XMKD /test/bb\r\n"); //执行服务器上的FTP命令ftpclient.readServerResponse一定要在sendServer后调用nameList("/test")获取指目录下的文件列表XMKD建立目录,当目录存在的情况下再次创建目录时报错XRMD删除目录DELE删除文件*/}}package com.ftp;p.FTPFile;import .ftp.FTPFileEntryParser;import .TelnetInputStream;public class FtpAppache {public FtpAppache() throws Exception{// .ftp.FtpClient ft = null;// TelnetInputStream t = ft.list();// t.setStickyCRLF(true);}public void test1() throws Exception {//String strTemp = "";//InetAddress ia = InetAddress.getByName("192.168.0.193");FTPClient ftp = new FTPClient();ftp.connect("172.16.0.142",22);boolean blogin = ftp.login("ivr", "ivr");if (!blogin) {System.out.println("连接失败");();ftp = null;return;}/*//如果是中文名必需进行字符集转换boolean bMakeFlag = ftp.makeDirectory(new String("测试目录".getBytes( "gb2312"), "iso-8859-1")); //在服务器创建目录//上传文件到服务器,目录自由创建File file = new File("c:\\test.properties");ftp.storeFile("test.properties",new FileInputStream(file));*/System.out.println(SystemName());FTPFile[] ftpFiles = ();if (ftpFiles != null) {for (int i = 0; i < ftpFiles.length; i++) {System.out.println(ftpFiles[i].getName());//System.out.println(ftpFiles[i].isFile());if (ftpFiles[i].isFile()) {FTPFile ftpf = new FTPFile();/*System.err.println(ftpf.hasPermission(FTPFile.GROUP_ACCESS,FTPFile.EXECUTE_PERMISSION));System.err.println("READ_PERMISSION="+ftpf.hasPermission( ER_ACCESS,FTPFile.READ_PERMISSION));System.err.println("EXECUTE_PERMISSION="+ftpf.hasPermission(FTPFile. USER_ACCESS,FTPFile.EXECUTE_PERMISSION));System.err.println("WRITE_PERMISSION="+ftpf.hasPermission(FTPFile.U SER_ACCESS,FTPFile.WRITE_PERMISSION));System.err.println(ftpf.hasPermission(FTPFile.WORLD_ACCESS,FTPFile.READ_PERMISSION));*/}//System.out.println(ftpFiles[i].getUser());}}//下载服务器文件FileOutputStream fos = new FileOutputStream("e:/proftpd-1.2.10.tar.gz");ftp.retrieveFile("proftpd-1.2.10.tar.gz",fos);fos.close();//改变ftp目录//ftp.changeToParentDirectory();//回到父目录//ftp.changeWorkingDirectory("");//转移工作目录//pletePendingCommand();////删除ftp服务器文件//ftp.deleteFile("");//注销当前用户,//ftp.logout();//ftp.structureMount("");();ftp = null;}/*** 封装好的东西是好用,碰到这种问题,我们就。
ftpclient方法FTPClient方法是一种用于实现FTP(File Transfer Protocol,文件传输协议)客户端的方法。
通过使用FTPClient方法,我们可以实现与FTP服务器的连接、文件上传、文件下载、文件删除等操作。
下面将详细介绍FTPClient方法的使用。
一、连接FTP服务器在使用FTPClient方法进行文件传输之前,首先需要与FTP服务器建立连接。
可以通过以下代码实现与FTP服务器的连接:```javaFTPClient ftpClient = new FTPClient();ftpClient.connect(server, port);ftpClient.login(username, password);```其中,server是FTP服务器的IP地址,port是FTP服务器的端口号,username和password分别是登录FTP服务器的用户名和密码。
二、上传文件至FTP服务器使用FTPClient方法可以方便地将本地文件上传至FTP服务器。
可以通过以下代码实现文件上传:```javaFile file = new File(localFilePath);InputStream inputStream = new FileInputStream(file);ftpClient.storeFile(remoteFilePath, inputStream);```其中,localFilePath是本地文件的路径,remoteFilePath是上传至FTP服务器后的文件路径。
三、从FTP服务器下载文件使用FTPClient方法可以方便地从FTP服务器下载文件。
可以通过以下代码实现文件下载:```javaOutputStream outputStream = new FileOutputStream(localFilePath);ftpClient.retrieveFile(remoteFilePath, outputStream);```其中,localFilePath是文件下载后保存的本地路径,remoteFilePath是FTP服务器上待下载文件的路径。
JAVA中的FtpClient与FTPClient,并实现jsp页面下载ftp服务器上的文件这段时间一直在研究Java如何访问Ftp,搞了一段时间了,也有一定的了解。
故此记录一下。
ftp和FTP我个人觉得FTP更符合我们程序员的口味,不管是方法命名还是API的详细与否,或者是开发平台的问题,FTP毕竟是Apache的东西,做的就是不错。
其实web开发中一般都会涉及到编码问题,所以web上传下载一定会有中文乱码的问题存在,而FTP对中文的支持比ftp要好多了。
使用ftpClient不需要导入其它jar包,只要你使用java语言开发就行了,而使用FTPClient 需要使用commons-net-1.4.1.jar和jakarta-oro-2.0.8.jar,当然jar版本随便你自己。
话不多说,上代码!FTP服务器的文件目录结构图:一、FtpClientFtpClient是属于JDK的包下面的类,但是jdkapi并没有对此作介绍,在中文支持上面也有一定的限制。
本段代码中的Ftp服务器的IP地址,用户名和密码均通过SystemConfig.properties文档获取Ftp_client.java[java]view plain copy1.package com.iodn.util;2.3.import java.io.ByteArrayOutputStream;4.import java.io.File;5.import java.io.FileInputStream;6.import java.io.FileOutputStream;7.import java.io.IOException;8.import java.util.ResourceBundle;9.import .TelnetInputStream;10.import .TelnetOutputStream;11.import .ftp.FtpClient;12.13.public class Ftp_client {14.15.//FTP客户端16.private FtpClient ftpClient;17.private ResourceBundle res=null;18./**19. * 连接FTP服务器20. * @param path 指定远程服务器上的路径21. */22.public Ftp_client(String path){23.24. res = ResourceBundle.getBundle("com.iodn.util.SystemConfig");//获取配置文件propeties文档中的数据25.try{26. ftpClient=new FtpClient(res.getString("Properties.ftpHostIp"));//如果不想使用配置文件即可将数据写死(如:192.168.1.10)27. ftpClient.login(res.getString("Properties.ftpUser"), res.getString("Properties.ftpPassword"));//Ftp服务器用户名和密码28. ftpClient.binary();29. System.out.println("Login Success!");30.if(path.length()!=0){31.//把远程系统上的目录切换到参数path所指定的目录(可不用设置,上传下载删除时加Ftp中的全路径即可)32. ftpClient.cd(path);33. }34. }catch(Exception e){35. e.printStackTrace();36. }37. }38.39./**40. * 上传文件41. * @param remoteFile42. * @param localFile43. */44.public boolean upload(String remoteFile, String localFile){45.boolean bool=false;46. TelnetOutputStream os=null;47. FileInputStream is=null;48.try{49. os=ftpClient.put(remoteFile);50. is=new FileInputStream(new File(localFile));51.byte[] b=new byte[1024];52.int c;53.while((c=is.read(b))!=-1){54. os.write(b, 0, c);55. }56. bool=true;57. }catch(Exception e){58. e.printStackTrace();59. System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动");60. }finally{61.if(is!=null){62.try {63. is.close();64. } catch (IOException e) {65. e.printStackTrace();66. }67. }68.if(os!=null){69.try {70. os.close();71. } catch (IOException e) {72. e.printStackTrace();74. }75. closeConnect();76. }77.return bool;78. }79./**80. * 下载文件81. * @param remoteFile 远程文件路径(服务器端)82. * @param localFile 本地文件路径(客户端)83. */84.85.public void download(String remoteFile, String localFile) {86. TelnetInputStream is=null;87. FileOutputStream os=null;88.try{89.//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
JAVA中使⽤FTPClient实现⽂件上传下载实例代码在java程序开发中,ftp⽤的⽐较多,经常打交道,⽐如说向FTP服务器上传⽂件、下载⽂件,本⽂给⼤家介绍如何利⽤jakarta commons中的FTPClient(在commons-net包中)实现上传下载⽂件。
⼀、上传⽂件原理就不介绍了,⼤家直接看代码吧/*** Description: 向FTP服务器上传⽂件* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param path FTP服务器保存⽬录* @param filename 上传到FTP服务器上的⽂件名* @param input 输⼊流* @return 成功返回true,否则返回false*/publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//连接FTP服务器//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(path);ftp.storeFile(filename, input);input.close();ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}<pre></pre>/*** Description: 向FTP服务器上传⽂件* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param path FTP服务器保存⽬录* @param filename 上传到FTP服务器上的⽂件名* @param input 输⼊流* @return 成功返回true,否则返回false*/public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//连接FTP服务器//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(path);ftp.storeFile(filename, input);input.close();ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}下⾯我们写两个⼩例⼦:1.将本地⽂件上传到FTP服务器上,代码如下:@Testpublicvoid testUpLoadFromDisk(){try {FileInputStream in=new FileInputStream(new File("D:/test.txt"));boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag);} catch (FileNotFoundException e) {e.printStackTrace();}}<pre></pre>@Testpublic void testUpLoadFromDisk(){try {FileInputStream in=new FileInputStream(new File("D:/test.txt"));boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", in); System.out.println(flag);} catch (FileNotFoundException e) {e.printStackTrace();}}2.在FTP服务器上⽣成⼀个⽂件,并将⼀个字符串写⼊到该⽂件中@Testpublicvoid testUpLoadFromString(){try {InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}<pre></pre>@Testpublic void testUpLoadFromString(){try {InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8")); boolean flag = uploadFile("127.0.0.1", 21, "test", "test", "D:/ftp", "test.txt", input); System.out.println(flag);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}⼆、下载⽂件从FTP服务器下载⽂件的代码也很简单,参考如下:/*** Description: 从FTP服务器下载⽂件* @Version. Jul , :: PM by 崔红保(cuihongbao@)创建* @param url FTP服务器hostname* @param port FTP服务器端⼝* @param username FTP登录账号* @param password FTP登录密码* @param remotePath FTP服务器上的相对路径* @param fileName 要下载的⽂件名* @param localPath 下载后保存到本地的路径* @return*/publicstaticboolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) { boolean success = false;FTPClient ftp = new FTPClient();try {int reply;ftp.connect(url, port);//如果采⽤默认端⼝,可以使⽤ftp.connect(url)的⽅式直接连接FTP服务器ftp.login(username, password);//登录reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return success;}ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器⽬录FTPFile[] fs = ftp.listFiles();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();}}ftp.logout();success = true;} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return success;}<pre></pre>。
河南理工大学计算机科学与技术学院课程设计报告2015— 2016学年第一学期课程名称计算机网络设计题目FTP客户端的设计与实现姓名*** *学号361309010410专业班级计科合1304指导教师孟慧2016年1 月9 日1目录第一章序言.................................................................................................................21.1课程设计题目 (3)1.2开发工具.........................................................................................3第二章系统需求分析...............................................................................................52.1功能需求.........................................................................................52.2 系统模型设计...................................................................................52.3 系统工作流程设计.. (5)第三章系统设计·········································································································63.1实现功能·························································································63.2函数说明·························································································63.2.1界面设计代码6 (3).2.2功能实现函数9 ......................................................................................第四章系统实现.......................................................................................................134.1界面设计的实现................................................................................314.1.1连接服务器.. (13)4.1.2获取文件列表 (13)4.1.3断开服务器 (14)4.1.4上传文件 (15)61..................................................下载...................................................4.1.54.1.6重命名.. (18)4.1.7删除 (19)4.1.8刷新 (20)4.1.9返回上一目录 (21)4.1.10查看日志信息 (21)第五章总结...............................................................................................................22第六章参考文献. (23)2序言第一章课程设计题目1.1FTP(File Transfer Protocol, FTP)是TCP/IP网络上两台计算机传送文件的协议,FTP是在TCP/IP网络和INTERNET上最早使用的协议之一,它属于网络协议组的应用层。
ftp客户端FileZilla Client 使用方法1.新建站点
注意主机地址,端口,以及协议(sftp,现在一般采用安全文件传输协议sftp)
2.站点连接
选择站点,点击连接,即实现与远程节点之间的连接
3.书签管理
书签管理可以实现本地目录与主机目录之间的同步功能,非常适用于开发阶段零散文件的上传。
3.1新建书签
先选择本地目录,在选择选择站点目录,然后点击添加书签,即可建立本地目录与远程目录的同步浏览。
3.2书签的使用
当连接到远程主机后,可使用书签实现目录同步浏览,避免繁琐的目录选择。
ftp之使⽤java将⽂件上传到ftp服务器上1. 在实际的应⽤重,通常是通过程序来进⾏⽂件的上传。
2. 实现java上传⽂件到ftp服务器中新建maven项⽬添加依赖<dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.3</version></dependency>测试:@Testpublic void testFtp1(){//创建客户端对象FTPClient ftp = new FTPClient();InputStream local=null;try {//连接ftp服务器ftp.connect("192.168.80.161", 21);//登录ftp.login("ftpuser", "1111");//设置上传路径String path="/home/ftpuser/image";//检查上传路径是否存在如果不存在返回falseboolean flag = ftp.changeWorkingDirectory(path);if(!flag){//创建上传的路径该⽅法只能创建⼀级⽬录,在这⾥如果/home/ftpuser存在则可创建imageftp.makeDirectory(path);}//指定上传路径ftp.changeWorkingDirectory(path);//指定上传⽂件的类型⼆进制⽂件ftp.setFileType(FTP.BINARY_FILE_TYPE);//读取本地⽂件File file = new File("mm.jpg");local = new FileInputStream(file);//第⼀个参数是⽂件名ftp.storeFile(file.getName(), local);} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {try {//关闭⽂件流local.close();//退出ftp.logout();//断开连接ftp.disconnect();} catch (IOException e) {e.printStackTrace();}}}3. 优化java上传代码: 如何解决上传的图⽚重名的问题?如果不解决,那么上传相同名称的图⽚将会覆盖之前⽂件。
java上传文件打到ftp注意点Java上传文件到ftp服务器;使用的Apache的commons-net-3.3.jar;try{ftpClient.connect("192.168.1.126");ftpClient.login("admin", "123");String f = transcoding("/XX归档文件");if(!ftpClient.changeWorkingDirectory(f)){ftpClient.makeDirectory(f);}ftpClient.changeWorkingDirectory(f);ftpClient.setBufferSize(1024);ftpClient.setControlEncoding("GBK");//设置文件类型(二进制)ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//fis是输入流ftpClient.storeFile(transcoding(fileName), fis);} catch(IOException e) {e.printStackTrace();} finally{IOUtils.closeQuietly(fis);ftpClient.disconnect(); //关闭连接}我们项目用的是IBM的unix小型机做的服务器;在unix往win8server的ftp上传文件是会出现以下的问题:1.ftpClient.makeDirectory("/AA/BB");类似多级文件夹时无法建立文件夹;2.文件夹或文件名过长时也无法建立;在自己电脑(win7)测试没有出现第一种问题.如果有第一种情况,就分级一层一层建立文件夹然后再建立对应的文件;还有为了避免中文乱码文化需要转码/*** 转码(FTP协议里面,规定文件名编码为iso-8859-1,所以只能建转码以后的目录和文件)*/public String transcoding(String str) throws UnsupportedEn codingException {return new String(str.getBytes("GBK"),"iso-8859-1");}。
Java课程设计-FTP客户端-说明书编辑整理:尊敬的读者朋友们:这里是精品文档编辑中心,本文档内容是由我和我的同事精心编辑整理后发布的,发布之前我们对文中内容进行仔细校对,但是难免会有疏漏的地方,但是任然希望(Java课程设计-FTP客户端-说明书)的内容能够给您的工作和学习带来便利。
同时也真诚的希望收到您的建议和反馈,这将是我们进步的源泉,前进的动力。
本文可编辑可修改,如果觉得对您有帮助请收藏以便随时查阅,最后祝您生活愉快业绩进步,以下为Java课程设计-FTP客户端-说明书的全部内容。
摘要FTP是Internet上最早也是最广的应用,直到今天它仍是最重要和最基本的应用之一.用FTP将信息下载到本地是一件十分普遍的事。
也随之出现了许多下载软件。
尽管远程登录(Telnet)提供了访问远程文件的极好方法,但怎么也比不上使用自己计算机中的文件方便。
如果用户想使用其它计算机上的文件,最理想的方法就是把它COPY到自己的计算机中,以便在本地计算机上操作。
FTP正是完成这项工作的工具,你可以在任意一个经过文件传输协议(FTP)访问的公共有效的联机数据库或文档中找到你想要的任何东西. FTP是Internet上用来传送文件的协议.它是为了我们能够在Internet上互相传送文件而制定的文件传送标准,规定了Internet上文件如何传送。
通过FTP协议,我们就可以跟Internet上的FTP服务器进行文件的上传或下载。
本文以实现一个简单易用的FTP客户端为目标,通过分析FTP协议的基本工作原理和FTP的数据传输原理,研究如何使用Java工具对FTP 客户端进行设计,选择Java类库中的ftpclient类来实现FTP客户端程序的上传下载等主要功能。
关键字:Ftp客户端、FTP协议、工作原理、上传下载目录引言。
.。
..。
.。
....。
....。
...。
.。
.。
......。
.。
.。
...。
..。
.......。
JavaFTP⽂件传输简单实现简单介绍下win7 上配置FTP服务和java实现FTP⼩练习。
如果是win7系统⾸先开启ftp服务控制⾯板->程序->打开关闭windows功能如图:打开ftp服务,然后开始配置ftp服务站点,打开管理服务,如下图:选择站点右击添加FTP站点如图:设置属性按照下⾯三个步骤就配置好⼀个本地ftp服务站点⾮常之简单如图:好了 FTP服务配置好了如何测试⼀下呢,这⾥先介绍⼀个FTP客户端软件,叫做FileZilla Client 简称 fz ⼀个很强⼤的FTP客户端下载安装很简单就不过多介绍了,看⼀下安装好了之后连接刚才建好的ftp的站点,因为是创建的匿名站点这⾥不需要密码,实际根据具情况配置站点。
测试下⾃⼰给⾃⼰电脑传⽂件,下载⽂件吧(感觉傻傻的样⼦…)。
接下来开始写有⽤的java连接TFP站点和传输⽂件的代码。
1.⾸先jar⽤的是apache 的⼯具包请⾃⾏下载2.俩个⽂件代码⼀个FtpConfig.java 和 FtpUtil.java 实现了上传,⽂件夹下载,和单⽂件下载详情如下均已测试。
FtpConfig.javapackage FTPDemo;/*** @date 2016年12⽉30⽇* @author xie**/public class FtpConfig {// 主机ipprivate String FtpHost;// 端⼝号private Integer FtpPort;// ftp⽤户名private String FtpUser;// ftp密码private String FtpPassword;// ftp中的⽬录private String FtpPath;public String getFtpHost() {return FtpHost;}public Integer getFtpPort() {return FtpPort;}public void setFtpPort(Integer ftpPort) {FtpPort = ftpPort;}public void setFtpHost(String ftpHost) {FtpHost = ftpHost;}public String getFtpUser() {return FtpUser;}public void setFtpUser(String ftpUser) {FtpUser = ftpUser;}public String getFtpPassword() {return FtpPassword;}public void setFtpPassword(String ftpPassword) {FtpPassword = ftpPassword;}public String getFtpPath() {return FtpPath;}public void setFtpPath(String ftpPath) {FtpPath = ftpPath;}}FtpUtil.javapackage FTPDemo;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.logging.Logger;import .ftp.FTPClient;import .ftp.FTPFile;import .ftp.FTPReply;public class FtpUtil {private static FTPClient ftp;/*** 获取ftp连接* @param f* @return* @throws Exception*/public static boolean connectFtp(FtpConfig f) throws Exception{ ftp=new FTPClient();boolean flag=false;if (f.getFtpPort()==null) {ftp.connect(f.getFtpHost(),21);}else{ftp.connect(f.getFtpHost(),f.getFtpPort());}ftp.login(f.getFtpUser(), f.getFtpPassword());int reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return flag;}ftp.changeWorkingDirectory(f.getFtpPath());flag = true;return flag;}/*** 关闭ftp连接*/public static void closeFtp(){try {if (ftp!=null && ftp.isConnected()) {ftp.logout();ftp.disconnect();}}catch (IOException e){e.printStackTrace();}}/*** ftp上传⽂件* @param f* @throws Exception*/public static void upload(File f) throws Exception{if (f.isDirectory()) {ftp.makeDirectory(f.getName());ftp.changeWorkingDirectory(f.getName());String[] files=f.list();for(String fstr : files){File file1=new File(f.getPath()+File.separator+fstr);if (file1.isDirectory()) {upload(file1);ftp.changeToParentDirectory();}else{File file2=new File(f.getPath()+File.separator+fstr);FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}}else{File file2=new File(f.getPath());FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}/*** 下载链接配置* @param f* @param localBaseDir 本地⽬录* @param remoteBaseDir 远程⽬录* @throws Exception*/public static void startDownDir(FtpConfig f,String localBaseDir,String remoteBaseDir) throws Exception{ if (FtpUtil.connectFtp(f)) {try {FTPFile[] files = null;boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);if (changedir) {ftp.setControlEncoding("UTF-8");files = ftp.listFiles();for (int i = 0; i < files.length; i++) {downloadFile(files[i], localBaseDir, remoteBaseDir);}}else{System.out.println("不存在的相对路径!");}} catch (Exception e) {e.printStackTrace();}}else{System.out.println("连接失败");}}public static void startDownFile(FtpConfig f,String localBaseDir,String remoteFilePath) throws Exception{ if (FtpUtil.connectFtp(f)) {try {FileOutputStream outputStream = new FileOutputStream(localBaseDir + remoteFilePath);ftp.retrieveFile(remoteFilePath, outputStream);outputStream.flush();outputStream.close();} catch (Exception e) {e.printStackTrace();}}else{System.out.println("连接FTP服务器失败");}}/**** 下载FTP⽂件* 当你需要下载FTP⽂件的时候,调⽤此⽅法* 根据<b>获取的⽂件名,本地地址,远程地址</b>进⾏下载** @param ftpFile* @param relativeLocalPath 下载到本地的绝对路径* @param relativeRemotePath 要下载的远程ftp服务器相对路径*/private static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { if (ftpFile.isFile()) {if (ftpFile.getName().indexOf("?") == -1) {OutputStream outputStream = null;try {File locaFile= new File(relativeLocalPath+ ftpFile.getName());//判断⽂件是否存在,存在则返回 or 直接覆盖if(locaFile.exists()){return;}else{outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); ftp.retrieveFile(ftpFile.getName(), outputStream);outputStream.flush();}} catch (Exception e) {e.printStackTrace();} finally {try {if (outputStream != null){outputStream.close();}} catch (IOException e) {e.printStackTrace();}}}} else {String newlocalRelatePath = relativeLocalPath + ftpFile.getName();String newRemote = relativeRemotePath + ftpFile.getName().toString();File fl = new File(newlocalRelatePath);if (!fl.exists()) {fl.mkdirs();}try {newlocalRelatePath = newlocalRelatePath+File.separator;newRemote = newRemote+File.separator;String currentWorkDir = ftpFile.getName().toString();//System.out.println(currentWorkDir);boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);if (changedir) {FTPFile[] files = null;files = ftp.listFiles();for (int i = 0; i < files.length; i++) {downloadFile(files[i], newlocalRelatePath, newRemote);}}if (changedir){ftp.changeToParentDirectory();}} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception{FtpConfig f=new FtpConfig();f.setFtpHost("192.168.3.100");f.setFtpPort(21);f.setFtpUser("anonymous");f.setFtpPassword("");// f.setFtpPath("/data1/");//相对路径FtpUtil.connectFtp(f);File file = new File("E:\\data1\\physics.txt");//FtpUtil.upload(file);//把⽂件上传在ftp上// FtpUtil.startDownFile(f, "E:/", "physics.txt");FtpUtil.startDownDir(f, "E:/data1/", "/data1/");}}。
解决FTPClient上传⽂件为空JAVA使⽤FTPClient上传⽂件时总是为空,⽽使⽤FileZilla客户端时却不会。
后来查了下资料,FTP服务器有被动模式和主动模式。
(具体查另外资料)在JAVA中将FTPClient设置为被动模式即可解决问题。
public void testFTPClient() throws Exception {try {//創建⼀個FTPClient對象FTPClient ftpClient = new FTPClient();//創建ftp連接ftpClient.connect("***.***.***.***", 21);//登錄ftp,使⽤⽤⼾名和密碼ftpClient.login("****", "****");//讀取本地⽂件FileInputStream inputStream = new FileInputStream(new File("filePath"));//設置為被動模式ftpClient.enterLocalPassiveMode();//設置上傳的路徑ftpClient.changeWorkingDirectory("FTP服务器⽂件⽬录");//修改上傳⽂件的格式ftpClient.setFileType(FTP.BINARY_FILE_TYPE);/*** 第⼀個參數:服務端⽂件名* 第⼆個參數:上傳⽂檔的InputStream*/System.out.println("1");//上傳⽂件ftpClient.storeFile("hello1.jpg", inputStream);System.out.println("2");//關閉連接ftpClient.logout();} catch (Exception e) {e.printStackTrace();throw e;}}。
Java中FTPClient上传中⽂⽬录、中⽂⽂件名乱码问题解决⽅法问题描述:使⽤.ftp.FTPClient创建中⽂⽬录、上传中⽂⽂件名时,⽬录名及⽂件名中的中⽂显⽰为“??”。
原因:FTP协议⾥⾯,规定⽂件名编码为iso-8859-1,所以⽬录名或⽂件名需要转码。
解决⽅案:1.将中⽂的⽬录或⽂件名转为iso-8859-1编码的字符。
参考代码:复制代码代码如下:String name="⽬录名或⽂件名";name=new String(name.getBytes("GBK"),"iso-8859-1");// 转换后的⽬录名或⽂件名。
2.设置linux环境变量复制代码代码如下:export LC_ALL="zh_CN.GBK"export LANG="zh_CN.GBK"实例:复制代码代码如下:public boolean upLoadFile(File file, String path, String fileName) throws IOException {boolean result = false;FTPClient ftpClient = new FTPClient();try {ftpClient.connect(confService.getConfValue(PortalConfContants.FTP_CLIENT_HOST));ftpClient.login(confService.getConfValue(PortalConfContants.FTP_CLIENT_USERNAME), confService.getConfValue(PortalConfContants.FTP_CLIENT_PASSWORD));ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// make directoryif (path != null && !"".equals(path.trim())) {String[] pathes = path.split("/");for (String onepath : pathes) {if (onepath == null || "".equals(onepath.trim())) {continue;}onepath=new String(onepath.getBytes("GBK"),"iso-8859-1");if (!ftpClient.changeWorkingDirectory(onepath)) {ftpClient.makeDirectory(onepath);ftpClient.changeWorkingDirectory(onepath);}}}result = ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), new FileInputStream(file));} catch (Exception e) {e.printStackTrace();} finally {ftpClient.logout();}return result; }。
Java实现SFTP客户端1、SFTP下载Excel并解析,调试代码public InputStream downloadFileStream(String remotePath,String regexFileName) {InputStream fielInput = null;String requireRemoteFileName = "";try {Vector v = listFiles(remotePath);// sftp.cd(remotePath);if (v.size() > 0) {("本次处理⽂件个数为fileSize={}", v.size());int matchFileMaxModifyTime = 0;Iterator it = v.iterator();while (it.hasNext()) {LsEntry entry = (LsEntry) it.next();String remoteFilename = entry.getFilename();if (remoteFilename.contains(regexFileName)) {SftpATTRS attrs = entry.getAttrs();if (attrs.getSize() > 0) {int mTime = attrs.getMTime();if (matchFileMaxModifyTime <= mTime) {matchFileMaxModifyTime = mTime;requireRemoteFileName = remoteFilename;}}}}}fielInput = sftp.get(remotePath + requireRemoteFileName);if (log.isInfoEnabled()) {("DownloadFile:" + requireRemoteFileName+ " success from sftp.");}return fielInput;} catch (SftpException e) {log.error("downloadFileStream error:{}", e);} finally {}return fielInput;}package sftp;import java.io.FileInputStream;import java.io.InputStream;import java.util.Properties;import org.apache.log4j.PropertyConfigurator;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import excel.ExcelUtils;public class SFTPTest {private static Logger log = LoggerFactory.getLogger(SFTPUtils.class);public static void main(String[] args) {logInit();// sftpTest();sftpTest02();}private static void sftpTest02() {String remotePath = "/sftpremote/";SFTPUtils sftp = null;InputStream inputStream = null;try {sftp = new SFTPUtils("127.0.0.1", "admin01", "123");sftp.connect();// 下载inputStream = sftp.downloadFileStream(remotePath, "201905");if (null != inputStream) {ExcelUtils.getDataFromExcel(inputStream);inputStream.close();}} catch (Exception e) {log.error("download error:{}", e);} finally {("sftp disconnect");sftp.disconnect();}}private static void sftpTest() {SFTPUtils sftp = null;// 本地存放地址,需要加最后的“\\”,才能下载到指定⽬录,否则是上⼀级⽬录 String localPath = "E:\\book\\sftptest\\sftpdownload\\";// Sftp下载路径String remotePath = "/sftpremote/";try {sftp = new SFTPUtils("127.0.0.1", "admin01", "123");sftp.connect();// 下载sftp.downloadFile(remotePath, "test.txt", localPath,"testLocal.txt");} catch (Exception e) {log.error("download error:{}", e);} finally {("sftp disconnect");sftp.disconnect();}}public static void logInit() {Properties logProp = new Properties();try {FileInputStream logIn = new FileInputStream("log4j.properties");logProp.load(logIn);logIn.close();PropertyConfigurator.configure(logProp);} catch (Exception e) {log.error("logInit error:{}", e);}}}package excel;import java.io.IOException;import java.io.InputStream;import ermodel.Cell;import ermodel.Row;import ermodel.Sheet;import ermodel.Workbook;import ermodel.XSSFWorkbook;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class ExcelUtils {private static Logger log = LoggerFactory.getLogger(ExcelUtils.class);public static void getDataFromExcel(InputStream inputStream) {Workbook wookbook = null;try {wookbook = new XSSFWorkbook(inputStream);} catch (IOException e) {e.printStackTrace();}// 得到⼀个⼯作表Sheet sheet = wookbook.getSheetAt(0);// 获得数据的总⾏数int totalRowNum = sheet.getLastRowNum();("totalRowNum:{}", totalRowNum);// 获得所有数据for (int i = 2; i <= totalRowNum; i++) {// 不搞反射,直接获取数据// 获得第i⾏对象Row row = sheet.getRow(i);// 获得获得第i⾏第0列的 String类型对象Cell cell = row.getCell(0);String row01 = cell.getStringCellValue().toString();// 获得获得第i⾏第1列的 String类型对象cell = row.getCell(1);int row02 = (int) cell.getNumericCellValue();("{} {}", row01, row02);}}}。
FTPClient⽤法某些数据交换,我们需要通过ftp来完成。
.ftp.FtpClient 可以帮助我们进⾏⼀些简单的ftp客户端功能:下载、上传⽂件。
但如遇到创建⽬录之类的就⽆能为⼒了,我们只好利⽤第三⽅源码,⽐如 .ftp.FTPClient 下⾯写⼀些.ftp.FtpClient 的使⽤⽅法。
1、引⼊包import java.io.DataInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.FileInputStream;import java.util.ArrayList;import java.util.Date;import java.util.List;import .*;import .ftp.FtpClient;2、我们建⼀个叫做FtpUtil的class/*** connectServer* 连接ftp服务器* @throws java.io.IOException* @param path ⽂件夹,空代表根⽬录* @param password 密码* @param user 登陆⽤户* @param server 服务器地址*/public void connectServer(String server, String user, String password, String path)throws IOException{// server:FTP服务器的IP地址;user:登录FTP服务器的⽤户名// password:登录FTP服务器的⽤户名的⼝令;path:FTP服务器上的路径ftpClient = new FtpClient();ftpClient.openServer(server);ftpClient.login(user, password);//path是ftp服务下主⽬录的⼦⽬录if (path.length() != 0) ftpClient.cd(path);//⽤2进制上传、下载ftpClient.binary();}/*** upload* 上传⽂件* @throws ng.Exception* @return -1 ⽂件不存在* -2 ⽂件内容为空* >0 成功上传,返回⽂件的⼤⼩* @param newname 上传后的新⽂件名* @param filename 上传的⽂件*/public long upload(String filename,String newname) throws Exception{long result = 0;TelnetOutputStream os = null;FileInputStream is = null;try {java.io.File file_in = new java.io.File(filename);if (!file_in.exists()) return -1;if (file_in.length()==0) return -2;os = ftpClient.put(newname);result = file_in.length();is = new FileInputStream(file_in);byte[] bytes = new byte[1024];int c;while ((c = is.read(bytes)) != -1) {os.write(bytes, 0, c);}} finally {if (is != null) {is.close();}if (os != null) {os.close();}}return result;}/*** upload* @throws ng.Exception* @return* @param filename*/public long upload(String filename)throws Exception{String newname = "";if (filename.indexOf("/")>-1){newname = filename.substring(stIndexOf("/")+1);}else{newname = filename;}return upload(filename,newname);}/*** download* 从ftp下载⽂件到本地* @throws ng.Exception* @return* @param newfilename 本地⽣成的⽂件名* @param filename 服务器上的⽂件名*/public long download(String filename,String newfilename)throws Exception{long result = 0;TelnetInputStream is = null;FileOutputStream os = null;try{is = ftpClient.get(filename);java.io.File outfile = new java.io.File(newfilename);os = new FileOutputStream(outfile);byte[] bytes = new byte[1024];int c;while ((c = is.read(bytes)) != -1) {os.write(bytes, 0, c);result = result + c;}} catch (IOException e){e.printStackTrace();}finally {if (is != null) {is.close();}if (os != null) {os.close();}}return result;}/*** 取得某个⽬录下的所有⽂件列表**/public List getFileList(String path){List list = new ArrayList();try{DataInputStream dis = new DataInputStream(List(path));String filename = "";while((filename=dis.readLine())!=null){list.add(filename);}} catch (Exception e){e.printStackTrace();}return list;}/*** closeServer* 断开与ftp服务器的链接* @throws java.io.IOException*/public void closeServer()public void closeServer()throws IOException{try{if (ftpClient != null){ftpClient.closeServer();}} catch (IOException e) {e.printStackTrace();}}public static void main(String [] args) throws Exception{FtpUtil ftp = new FtpUtil();try {//连接ftp服务器ftp.connectServer("10.163.7.15", "cxl", "1", "info2");/** 上传⽂件到 info2 ⽂件夹下 */System.out.println("filesize:"+ftp.upload("f:/download/Install.exe")+"字节");/** 取得info2⽂件夹下的所有⽂件列表,并下载到 E盘下 */List list = ftp.getFileList(".");for (int i=0;i<list.size();i++){String filename = (String)list.get(i);System.out.println(filename);ftp.download(filename,"E:/"+filename);}} catch (Exception e) {///}finally{ftp.closeServer();}}}。
使⽤FTPClient实现⽂件上传服务器import ch.qos.logback.classic.Logger;import .ftp.*;import org.slf4j.LoggerFactory;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.List;public class uploadutil {public final static Logger logger= (Logger) LoggerFactory.getLogger(uploadutil.class);private static String ftpip=propertiesutil.getValue("ftp.server.ip");private static String ftpuser=propertiesutil.getValue("er");private static String ftppass=propertiesutil.getValue("ftp.password");private int port;private String ip;private String user;private String pass;private FTPClient ftpClient;public uploadutil(int port, String ip, String user, String pass) {this.port = port;this.ip = ip;er = user;this.pass = pass;}public String getUser() {return user;}public void setUser(String user) {er = user;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public FTPClient getFtpClient() {return ftpClient;}public void setFtpClient(FTPClient ftpClient) {this.ftpClient = ftpClient;}public String getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}public static boolean uploadok(List<File> filelist) throws IOException {uploadutil u=new uploadutil(14147,ftpip,ftpuser,ftppass);("start upload");boolean result=u.uploads("work",filelist);("end upload");return result;}private boolean uploads(String remotepath,List<File> listfile) throws IOException {boolean upload=true;FileInputStream f=null;if(connectserver(this.getPort(),this.getIp(),this.getUser(),this.pass)){try {ftpClient.changeWorkingDirectory(remotepath);ftpClient.setBufferSize(1024);ftpClient.setControlEncoding("utf-8");ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);ftpClient.enterLocalPassiveMode();for(File file:listfile){f=new FileInputStream(file);ftpClient.storeFile(file.getName(),f);}} catch (IOException e) {logger.error("⽂件上传异常",e);upload=false;e.printStackTrace();}finally {f.close();ftpClient.disconnect();}}return upload;}private boolean connectserver(int port, String ip, String user, String pass){ ftpClient=new FTPClient();boolean isok=false;try {ftpClient.connect(ip);isok=ftpClient.login(user,pass);} catch (IOException e) {logger.error("链接服务器异常",e);}return isok;}}。
1。
采用Apache.FTPClient:/*** Apache.FTPClient FTP操作共公类** @author 张明学**/public class FTPCommon {private FTPClient ftpClient;private FTPModel ftpModel;public FTPCommon(FTPModel ftp) {super();// 从配置文件中读取初始化信息this.ftpClient = new FTPClient();this.ftpModel = ftp;}/*** 连接并登录FTP服务器**/public boolean ftpLogin() {boolean isLogin = false;FTPClientConfig ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);ftpClientConfig.setServerTimeZoneId(TimeZone.getDefaul t().getID());this.ftpClient.setControlEncoding("GBK");this.ftpClient.configure(ftpClientConfig);try {if (this.ftpModel.getPort() > 0) {this.ftpClient.connect(ftpModel.getUrl(), ftpModel.getPort());} else {this.ftpClient.connect(ftpModel.getUrl());}// FTP服务器连接回答int reply = this.ftpClient.getR eplyCode();if (!FTPReply.isPositiveCompletion(reply)) {this.ftpClient.disconnect();return isLogin;}this.ftpClient.login(this.ftpModel.getUsername(), this.ftpModel.getPassword());this.ftpClient.changeWorkingDirectory(this.ftpModel.getR emoteDir());this.ftpClient.setFileType(FTPClient.FILE_STRUCTURE);OutPut("成功登陆FTP服务器:" + this.ftpModel.getUrl() + " 端口号:"+ this.getFtpModel().getPort() + " 目录:"+ this.ftpModel.getRemoteDir());isLogin = true;} catch (SocketException e) {e.printStackTrace();LogUtil.logPrint("连接FTP服务失败!", Constants.LOG_EXCEPTION);LogUtil.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);} catch (IOException e) {e.printStackTrace();LogUtil.logPrint("登录FTP服务失败!", Constants.LOG_EXCEPTION);LogUtil.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);}System.out.println(this.ftpClient.getBufferSize());this.ftpClient.setBufferSize(1024 * 2);this.ftpClient.setDataTimeout(2000);return isLogin;}/*** 退出并关闭FTP连接**/public void close() {if (null != this.ftpClient && this.ftpClient.isConnected()) {try {boolean reuslt = this.ftpClient.logout();// 退出FTP服务器if (reuslt) {("退出并关闭FTP服务器的连接");}} catch (IOException e) {e.printStackTrace();LogUtil.exception("退出FTP服务器异常!");LogUtil.exception(e.getMessage());} finally {try {this.ftpClient.disconnect();// 关闭FTP服务器的连接} catch (IOException e) {e.printStackTrace();LogUtil.exception("关闭FTP服务器的连接异常!");LogUtil.exception(e.getMessage());}}}}/*** 检查FTP服务器是否关闭,如果关闭接则连接登录FTP** @return*/public boolean isOpenFTPConnection() {boolean isOpen = false;if (null == this.ftpClient) {return false;}try {// 没有连接if (!this.ftpClient.isConnected()) {isOpen = this.ftpLogin();}} catch (Exception e) {e.printStackTrace();LogUtil.exception("FTP服务器连接登录异常!");LogUtil.exception(e.getMessage());isOpen = false;}return isOpen;}/*** 设置传输文件的类型[文本文件或者二进制文件]** @param fileType--FTPClient.BINAR Y_FILE_TYPE,FTPClient.ASCII_FILE_TYPE */public void setFileType(int fileType) {try {this.ftpClient.setFileType(fileType);} catch (IOException e) {e.printStackTrace();LogUtil.exception("设置传输文件的类型异常!");LogUtil.exception(e.getMessage());}}/*** 下载文件** @param localFilePath* 本地文件名及路径* @param remoteFileName* 远程文件名称* @return*/public boolean downloadFile(String localFilePath, String remoteFileName) { BufferedOutputStream outStream = null;boolean success = false;try {outStream = new BufferedOutputStream(new FileOutputStream(localFilePath));success = this.ftpClient.retrieveFile(remoteFileName, outStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (outStream != null) {try {outStream.flush();outStream.close();} catch (IOException e) {e.printStackTrace();}}}return success;}/*** 下载文件** @param localFilePath* 本地文件* @param remoteFileName* 远程文件名称* @return*/public boolean downloadFile(File localFile, String remoteFileName) {BufferedOutputStream outStream = null;FileOutputStream outStr = null;boolean success = false;try {outStr = new FileOutputStream(localFile);outStream = new BufferedOutputStream(outStr);success = this.ftpClient.retrieveFile(remoteFileName, outStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != outStream) {try {outStream.flush();outStream.close();} catch (IOException e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();} finally {if (null != outStr) {try {outStr.flush();outStr.close();} catch (IOException e) {e.printStackTrace();}}}}return success;}/*** 上传文件** @param localFilePath* 本地文件路径及名称* @param remoteFileName* FTP 服务器文件名称* @return*/public boolean uploadFile(String localFilePath, String remoteFileName) { BufferedInputStream inStream = null;boolean success = false;try {inStream = new BufferedInputStream(new FileInputStream(localFilePath));success = this.ftpClient.storeFile(remoteFileName, inStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (inStream != null) {try {inStream.close();} catch (IOException e) {e.printStackTrace();}}}return success;}/*** 上传文件** @param localFilePath* 本地文件* @param remoteFileName* FTP 服务器文件名称* @return*/public boolean uploadFile(File localFile, String remoteFileName) {BufferedInputStream inStream = null;boolean success = false;try {inStream = new BufferedInputStream(new FileInputStream(localFile));success = this.ftpClient.storeFile(remoteFileName, inStream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (inStream != null) {try {inStream.close();} catch (IOException e) {e.printStackTrace();}}}return success;}/*** 变更工作目录** @param remoteDir--目录路径*/public void changeDir(String remoteDir) {try {this.ftpClient.changeWorkingDirectory(remoteDir);("变更工作目录为:" + remoteDir);} catch (IOException e) {e.printStackTrace();LogUtil.exception("变更工作目录为:" + remoteDir + "时出错!");LogUtil.exception(e.getMessage());}}* 变更工作目录** @param remoteDir--目录路径*/public void changeDir(String[] remoteDirs) {String dir = "";try {for (int i = 0; i < remoteDirs.length; i++) {this.ftpClient.changeWorkingDirectory(remoteDirs[i]);dir = dir + remoteDirs[i] + "/";}("变更工作目录为:" + dir);} catch (IOException e) {e.printStackTrace();LogUtil.exception("变更工作目录为:" + dir + "时出错!");LogUtil.exception(e.getMessage());}}/*** 返回上级目录**/public void toParentDir(String[] remoteDirs) {try {for (int i = 0; i < remoteDirs.length; i++) {this.ftpClient.changeToParentDirectory();}("返回上级目录");} catch (IOException e) {e.printStackTrace();LogUtil.exception("返回上级目录时出错!");LogUtil.exception(e.getMessage());}}/*** 返回上级目录**/public void toParentDir() {try {this.ftpClient.changeToParentDirectory();("返回上级目录");} catch (IOException e) {e.printStackTrace();LogUtil.exception("返回上级目录时出错!");LogUtil.exception(e.getMessage());}}/*** 获得FTP 服务器下所有的文件名列表** @param regex* @returnpublic String[] getListFiels() {String files[] = null;try {files = this.ftpClient.listNames();} catch (IOException e) {e.printStackTrace();}return files;}public FTPClient getFtpClient() {return ftpClient;}public FTPModel getFtpModel() {return ftpModel;}public void setFtpModel(FTPModel ftpModel) {this.ftpModel = ftpModel;}}2。
Java操作ftpClient常用方法
1.连接FTP服务器
- connect(host: String, port: int): 建立与FTP服务器的连接。
- login(username: String, password: String): 登录FTP服务器。
2.设置工作目录
- changeWorkingDirectory(path: String): 切换当前工作目录。
- printWorkingDirectory(: 获取当前工作目录。
- storeFile(remoteFileName: String, inputStream: InputStream): 上传文件到FTP服务器。
4.删除文件
- deleteFile(remoteFileName: String): 删除FTP服务器上的文件。
5.列出目录中的文件
- listFiles(remotePath: String): 返回指定目录中的文件列表。
6.创建和删除目录
- makeDirectory(directory: String): 在FTP服务器上创建目录。
- removeDirectory(directory: String): 删除FTP服务器上的目录。
7.设置传输模式和文件类型
- setFileType(fileType: int): 设置文件类型(ASCII或二进制)。
- setFileTransferMode(mode: int): 设置传输模式(主动或被动)。
8.设置数据连接模式
- enterLocalPassiveMode(: 设置被动模式。
- enterLocalActiveMode(: 设置主动模式。
9.设置缓冲大小和字符编码
- setBufferSize(bufferSize: int): 设置缓冲区大小。
- setControlEncoding(encoding: String): 设置字符编码。
10.断开与FTP服务器的连接
- logout(: 登出FTP服务器。
- disconnect(: 断开与FTP服务器的连接。