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操作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服务器的连接。