Java_FTP文件上传下载

合集下载

java实现ftp的几种方式_java实现ftp的几种方式

java实现ftp的几种方式_java实现ftp的几种方式

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;}/*** 封装好的东西是好用,碰到这种问题,我们就。

java实现FTP文件上传与文件下载

java实现FTP文件上传与文件下载

java实现FTP⽂件上传与⽂件下载本⽂实例为⼤家分享了两种java实现FTP⽂件上传下载的⽅式,供⼤家参考,具体内容如下第⼀种⽅式:package com.cloudpower.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import .TelnetInputStream;import .TelnetOutputStream;import .ftp.FtpClient;/*** Java⾃带的API对FTP的操作* @Title:Ftp.java* @author: 周玲斌*/public class Ftp {/*** 本地⽂件名*/private String localfilename;/*** 远程⽂件名*/private String remotefilename;/*** FTP客户端*/private FtpClient ftpClient;/*** 服务器连接* @param ip 服务器IP* @param port 服务器端⼝* @param user ⽤户名* @param password 密码* @param path 服务器路径* @author 周玲斌* @date 2012-7-11*/public void connectServer(String ip, int port, String user,String password, String path) {try {/* ******连接服务器的两种⽅法*******///第⼀种⽅法// ftpClient = new FtpClient();// ftpClient.openServer(ip, port);//第⼆种⽅法ftpClient = new FtpClient(ip);ftpClient.login(user, password);// 设置成2进制传输ftpClient.binary();System.out.println("login success!");if (path.length() != 0){//把远程系统上的⽬录切换到参数path所指定的⽬录ftpClient.cd(path);}ftpClient.binary();} catch (IOException ex) {ex.printStackTrace();throw new RuntimeException(ex);}}/*** 关闭连接* @author 周玲斌* @date 2012-7-11*/public void closeConnect() {try {ftpClient.closeServer();System.out.println("disconnect success");} catch (IOException ex) {System.out.println("not disconnect");ex.printStackTrace();throw new RuntimeException(ex);}}/*** 上传⽂件* @param localFile 本地⽂件* @param remoteFile 远程⽂件* @author 周玲斌* @date 2012-7-11*/public void upload(String localFile, String remoteFile) {this.localfilename = localFile;this.remotefilename = remoteFile;TelnetOutputStream os = null;FileInputStream is = null;try {//将远程⽂件加⼊输出流中os = ftpClient.put(this.remotefilename);//获取本地⽂件的输⼊流File file_in = new File(this.localfilename);is = new FileInputStream(file_in);//创建⼀个缓冲区byte[] bytes = new byte[1024];int c;while ((c = is.read(bytes)) != -1) {os.write(bytes, 0, c);}System.out.println("upload success");} catch (IOException ex) {System.out.println("not upload");ex.printStackTrace();throw new RuntimeException(ex);} finally{try {if(is != null){is.close();}} catch (IOException e) {e.printStackTrace();} finally {try {if(os != null){os.close();}} catch (IOException e) {e.printStackTrace();}}}}/*** 下载⽂件* @param remoteFile 远程⽂件路径(服务器端)* @param localFile 本地⽂件路径(客户端)* @author 周玲斌* @date 2012-7-11*/public void download(String remoteFile, String localFile) {TelnetInputStream is = null;FileOutputStream os = null;try {//获取远程机器上的⽂件filename,借助TelnetInputStream把该⽂件传送到本地。

关于文件上传与下载的实现方法总结

关于文件上传与下载的实现方法总结

现就JA V A中文件上传与下载的实现方法总结如下:一、上传方法1.http方式:2)架包mons.fileupload.servlet.ServletFileUpload3)架包com.jspsmart.upload.SmartUpload4)架包jspupload5)传统fileinputstream,fileoutputstream方式6)struts框架支持2.FTP方式:1)sun的架包2)架包.ftp.FTPClient 比较好用3)架包.ftp.FTPClient二、下载方法1.http方式1)servlet+传统fileinputstream,fileoutputstream2)架包.ftp.FTPClient2.FTP方式:1)servlet+架包.ftp.FTPClient 比较好用下面就架包.ftp.FTPClient实现文件上传与下载。

代码如下:上传:JSP:<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html><head><title>文件上传</title></head><body><form action="/struts2HibernateSpring/servlet/uploadServletA" method="post">文件位置:<input type="file" name="mfile"><br><input type="submit" value="提交"></form></body></html>SERVLET:package com.test;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class UploadServletA extends HttpServlet {private static final long serialVersionUID = 1L;public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try{request.setCharacterEncoding("utf-8");response.setCharacterEncoding("UTF-8");response.setContentType("text/html; charset=UTF-8");String myFile = request.getParameter("mfile"); //获取页面提交的文件int indexOf = stIndexOf("\\"); //获取最后一个“/”所在的索引位String fileName = myFile.substring(indexOf); //获取文件上传的文件名//创建输出流把指定的文件写入WEB工程的upload目录下(需要在WebRoot目录下创建upload目录)。

Java文件上传与文件下载实现方法详解

Java文件上传与文件下载实现方法详解

Java⽂件上传与⽂件下载实现⽅法详解本⽂实例讲述了Java⽂件上传与⽂件下载实现⽅法。

分享给⼤家供⼤家参考,具体如下:Java⽂件上传数据上传是客户端向服务器端上传数据,客户端向服务器发送的所有请求都属于数据上传。

⽂件上传是数据上传的⼀种特例,指客户端向服务器上传⽂件。

即将保存在客户端的⽂件上传⼀个副本到服务器,并保存在服务器中。

1、上传表单要求⽂件上传要求客户端提交特殊的请求——multipart请求,即包含多部分数据的请求。

必须将<form/>标签的enctype属性值设为“multipart/form-data”,enctype表⽰encodingType,及编码类型由于客户端上传⽂件的⼤⼩是不确定的,所以http协议规定,⽂件上传的数据要存放于请求正⽂中,不能出现在URL地址栏内。

也就是说,想要上传⽂件必须提交POST请求。

表单中要有<input type="file" />标签注意:multipart/form-data请求与普通请求不同2、下载⽂件上传jar包并查看官⽅⽂档选择Commons中的FileUpload项⽬,并下载jar包和源⽂件查看FileUpload的⼯作⽅式查看FileUpload项⽬的API3、使⽤第三⽅jar包上传⽂件public class RegisterServlet extends HttpServlet {private static final long serialVersionUID = 1L;public RegisterServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.getWriter().append("Served at: ").append(request.getContextPath());}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//第⼀步、判断请求是否为multipart请求if(!ServletFileUpload.isMultipartContent(request)) {throw new RuntimeException("当前请求只⽀持⽂件上传");}try {//第⼆步、创建FileItem⼯⼚DiskFileItemFactory factory = new DiskFileItemFactory();//设置临时⽂件存储⽬录String path = this.getServletContext().getRealPath("/Temp");File temp = new File(path);factory.setRepository(temp);//单位:字节。

ftpclient方法

ftpclient方法

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文件输入输出流实现文件上传下载功能

基于Java文件输入输出流实现文件上传下载功能

基于Java⽂件输⼊输出流实现⽂件上传下载功能本⽂为⼤家分享了Java实现⽂件上传下载功能的具体代码,供⼤家参考,具体内容如下前端通过form表单的enctype属性,将数据传递⽅式修改为⼆进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息,运⽤java I/O 流的基础操作将流写⼊到⼀个服务端临时创建的⽂件temp中,然后再次利⽤⽂件基本操作,读取并截取临时⽂件内容,根据其中信息创建相应的⽂件,将读取出来的具体信息写⼊,下载时,根据提交的⽂件名称,找到服务器端相应的⽂件,然后根据输出流outStream输出到页⾯,同时将servlet的响应类型和响应头进⾏设置。

具体传输流程如下图:流信息的部分为:具体代码如下:前端代码:<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script src="Js/jquery.js"></script></head><body><form action="FileUpServlet" method="post" enctype="multipart/form-data"><table><tr><td>请选择上传⽂件:</td><td><input id="myfile" name="myfile" type="file" value="" /></td><td><input type="submit" value="上传"></td></tr><tr><td>${info}</td></tr></table></form>⽂件下载:<a href="FileLoadownServlet?filename=${filename}">${filename}</a></body></html>上传servlet部分(核⼼)@WebServlet("/FileUpServlet")public class FileUpServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public FileUpServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubdoPost(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");InputStream filesource = request.getInputStream();//request获取流信息String tempname = "D:/temp";//tempfile代表临时存放⽂件File tempfile = new File(tempname);//创建临时⽂件FileOutputStream outputStream = new FileOutputStream(tempfile);//输出流对象,指定输出指tempfile⽬录下byte b[] = new byte[1024];int n;while((n = filesource.read(b))!= -1)//从输出流中每次读取1024字节,直⾄读完{outputStream.write(b,0,n);}outputStream.close();filesource.close();//关闭输⼊输出流/*以下为具体的⽂件操作,主要为解析临时产⽣的 temp⽂件,知识多为java输⼊输出流的内容!*/RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//随机流,指定要读临时⽂件,只读randomfile.readLine();//读取第⼀⾏,⽆效数据,不需要String str = randomfile.readLine();//读取第⼆⾏int beginIndex = stIndexOf("=")+2;//指定所需数据的开始位置int endIndex = stIndexOf("\"");//指定所需数据截⾄位置String filename = str.substring(beginIndex,endIndex);//截取⽂件名//重新定位⽂件指针,获取⽂件内容randomfile.seek(0);//⽂件指针从头开始long startext = 0;int i = 1;//⽂件内容开始位置while((n=randomfile.readByte()) != -1&&i <= 4){if(n=='\n'){startext = randomfile.getFilePointer();i++;}}startext = randomfile.getFilePointer() - 1;//获取⽂件内容结束位置randomfile.seek(randomfile.length());long endtext = randomfile.getFilePointer();int j = 1;while(endtext >= 0 && j <= 2){endtext--;randomfile.seek(endtext);if(randomfile.readByte()=='\n'){j++;}}endtext = endtext-1;//将临时⽂件保存⾄指定⽬录中String realpath = getServletContext().getRealPath("/")+"images";//设置⽂件保存⽬录System.out.println(realpath);File fileupload = new File(realpath);if(!fileupload.exists()){fileupload.mkdir();//⽬录不存在则创建}File savefile = new File(realpath,filename);RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw");randomfile.seek(startext);while(startext<endtext){randomAccessFile.write(randomfile.readByte());//⽂件写⼊startext = randomfile.getFilePointer();}//关闭各种输⼊输出流randomAccessFile.close();randomfile.close();tempfile.delete();//删除临时⽂件SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date nowdate = new Date();String time = timed.format(nowdate.getTime());request.setAttribute("info", time+" "+filename+"上传成功!");request.setAttribute("filename", filename);request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}下载部分protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubString filename = request.getParameter("filename");String path = getServletContext().getRealPath("/")+"images/";File file = new File(path+filename);//找到⽂件if(file.exists())response.setContentType("application/x-msdownload"); //设置响应类型,此处为下载类型response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");//以附件的形式打开 InputStream inputStream = new FileInputStream(file);ServletOutputStream outputStream = response.getOutputStream();byte b[] = new byte[1024];int n;while((n = inputStream.read(b)) != -1){outputStream.write(b,0,n);}outputStream.close();inputStream.close();}else{request.setAttribute("result", "⽂件不存在!下载失败!");request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

JAVA中使用FTPClient实现文件上传下载实例代码

JAVA中使用FTPClient实现文件上传下载实例代码

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>。

java实现文件上传和下载

java实现文件上传和下载

java实现⽂件上传和下载本⽂实例为⼤家分享了java实现⽂件上传和下载的具体代码,供⼤家参考,具体内容如下⽂件的上传upload:⽂件上传客户端通过表单的⽂件域file 把客户端的⽂件上传保存到服务器的硬盘上页⾯⾸先对上传的表单有以下要求:必须有⽂件域:input type=file表单提交⽅式:method=post表单的 enctype=multipart/form-data<form method="post" action="/user/regist" enctype="multipart/form-data"><table style="border: chartreuse;solid:2px"><tr><th>⽤户名</th><td><input type="text" name="username"></td></tr><tr><th>密码</th><td><input type="password" name="password"></td></tr><tr><th>⽤户头像</th><td><input type="file" name="photo"> </td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form>Servlet1)⾸先要导⼊以下两个jar包,通过commons-fileupload实现⽂件上传2)创建⼀个⼯⼚对象DiskFileItemFactory,在创建⼀个多部件表单解析器ServletFileUpload,构造⽅法传⼊⼯⼚对象3)解析器解析请求对象,获得⼀个list集合,其中list集合存储的是⼀个⼀个的fileItem对象,⼀个fileItem对应⼀个组件,也就是⼀个<input>4) 遍历集合⽤isFormField()⽅法判断是否为普通组件,然后着重处理⽂件域组件5)获取⽂件名,并⽤getRealPath⽅法获取服务器上传⽂件所在路径,创建新⽂件夹6)获取输⼊流和创建输出流,进⾏⽂件的读写@WebServlet(value = "/user/regist")public class UploadServlet extends HttpServlet {protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//创建⼀个⼯⼚对象DiskFileItemFactory factory = new DiskFileItemFactory();//创建⼀个多部件解析器对象ServletFileUpload fileUpload = new ServletFileUpload(factory);User user = new User();FileOutputStream out=null;try {//⽤解析器对象解析请求,返回⼀个FileItem类型的集合List<FileItem> list = fileUpload.parseRequest(req);for (FileItem fileItem : list) {/*** fileItem.getFieldName());:::获取组件的name值* fileItem.getName());::::获取⽂件域的⽂件名* fileItem.getSize());::::获取数据的字节个数* fileItem.getString());::::获取数据的字符串* fileItem.isFormField());:::判断是否为普通组件*///判断部件是否为普通组件if (fileItem.isFormField()) {//普通组件//获取组件名字也就是name的值String fieldName = fileItem.getFieldName();//获取组件的值也就是value的值String value = fileItem.getString("utf-8");if ("username".equals(fieldName)) { //设置实体类的属性user.setUsername(value);} else if ("password".equals(fieldName)) {user.setPassword(value);}} else {// ⽂件域//获取⽂件名String fielName = fileItem.getName();//输⼊流来读数据InputStream in = fileItem.getInputStream();//设置⽂件写出的路径,并⽤随机码来保证图⽚可以重复String path=req.getServletContext().getRealPath("/imgs/"+ UUID.randomUUID()+fielName);System.out.println("⽂件路径为:"+path);File file = new File(path);out = new FileOutputStream(file);//利⽤commons-io-1.4.jar的IOUtils的copy⽅法直接实现⽂件的复制IOUtils.copy(in,out);user.setPhoto(file.getName());}}} catch (Exception e) {e.printStackTrace();}finally {if(out!=null){out.close();}}req.getSession().setAttribute("user",user);req.getRequestDispatcher("/sucess.jsp").forward(req,resp);}}⽂件的下载页⾯只需⼀个超链接,传需要下载的⽂件名,或者直接输⼊路径在浏览器例: <a href="<c:url value='/file/download?fileName=14.jpg'/>" >狗狗1</a><br/>Servlet1)接收参数,获取⽂件名2)获取imgs的路径,也就是存储⽂件的⽂件夹的路径,然后创建⽂件,传⼊该路径和⽂件名3)创建输⼊流读取⽂件4)设置响应头,⾸先根据⽂件名字获取⽂件的⼤类型,设置响应头Content-Type指定响应的类型;设置响应头Content-Disposition,指定⽂件以附件形式保存到本地磁盘5)⽤响应获取输出流,读出⽂件到客户端@WebServlet("/user/download")public class DownloadServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");//获取要下载的⽂件名String fileName = request.getParameter("fileName");System.out.println(fileName);//获取服务器中存储图⽚的⽂件夹的路径String path1 = request.getServletContext().getRealPath("/imgs");String path=path1+"/"+fileName;File file = new File(path);//创建输⼊流读⽂件FileInputStream in = new FileInputStream(file);//通过⽂件名字获取⽂件的⼤类型String type = request.getServletContext().getMimeType(fileName);//设置响应头ContentType指定响应内容的类型response.setHeader("Content-type",type);//设置响应头Content-Disposition 指定以附件形式保存响应的信息response.setHeader("Content-Disposition","attachment;filename="+(URLEncoder.encode(fileName, "utf-8"))); ServletOutputStream out = response.getOutputStream();//实现⽂件的读写IOUtils.copy(in,out);if(in!=null){in.close();}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

18.Javaweb中文件的上传和下载【重要】

18.Javaweb中文件的上传和下载【重要】

18.Javaweb中⽂件的上传和下载【重要】Javaweb中⽂件的上传和下载⽂件上传⽂件上传指的是⽤户通过浏览器向服务器上传某个⽂件,服务器接收到该⽂件后会将该⽂件存储在服务器的硬盘中,通常不会存储在数据库中,这样可以减轻数据库的压⼒并且在⽂件的操作上更加灵活,常见的功能是上传头像图⽚。

⽂件上传的原理所谓的⽂件上传就是服务器端通过request对象获取输⼊流,将浏览器端上传的数据读取出来,保存到服务器端。

⽂件上传的要求提供form表单,表单的提交⽅式必须是post【get请求装不下那么多】form表单中的enctype属性必须是 multipart/form-data 【照着做就⾏】表单中提供input type=”file”上传输⼊域 【⽂件那个表单】先来个表单:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><figure><img src=""></figure><form action="#" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <!--# 提交地址记得改!--><input type="file" name="photo"><br><input type="submit" value="上传头像"></form></body></html>来个Servlet来接收⼀下这个图⽚:package upload;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** ⽂件上传例⼦*/public class file extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求的输⼊流InputStream is = request.getInputStream();//读取输⼊流中的数据int leng = 0;byte[] bytes = new byte[1024];while ((leng = is.read(bytes)) != -1) {//先打印控制台看看System.out.println(new String(bytes,0,leng));}}}打印出来的数据:------WebKitFormBoundarypM4ZEsxzVdl0NfZVContent-Disposition: form-data; name="photo"; filename="4-2 鍥剧墖鍒囨崲鏁堟灉[20210508-164643].jpg"Content-Type: image/jpeg反正⼀堆乱码但是头部我们是看的懂的就是⼀些标签的属性和上传的照⽚名字!和⽂件类型!如何解决?请看:FileUpload⼯具的使⽤在实际开发中通常会借助第三⽅⼯具来实现上传功能,应⽤较多的是apache旗下的Commons-fileupload。

JavaWeb实现文件上传下载功能实例详解

JavaWeb实现文件上传下载功能实例详解

JavaWeb实现⽂件上传下载功能实例详解在Web应⽤系统开发中,⽂件上传和下载功能是⾮常常⽤的功能,今天来讲⼀下JavaWeb中的⽂件上传和下载功能的实现。

⽂件上传概述1、⽂件上传的作⽤例如⽹络硬盘!就是⽤来上传下载⽂件的。

在智联招聘上填写⼀个完整的简历还需要上传照⽚呢。

2、⽂件上传对页⾯的要求上传⽂件的要求⽐较多,需要记⼀下:必须使⽤表单,⽽不能是超链接表单的method必须是POST,⽽不能是GET表单的enctype必须是multipart/form-data在表单中添加file表单字段,即<input type=”file” name=”xxx”/><form action="${pageContext.request.contextPath }/FileUploadServlet"method="post" enctype="multipart/form-data">⽤户名:<input type="text" name="username"/><br/>⽂件1:<input type="file" name="file1"/><br/>⽂件2:<input type="file" name="file2"/><br/><input type="submit" value="提交"/></form>3、⽐对⽂件上传表单和普通⽂本表单的区别通过httpWatch查看“⽂件上传表单”和“普通⽂本表单”的区别。

⽂件上传表单的enctype=”multipart/form-data”,表⽰多部件表单数据;普通⽂本表单可以不设置enctype属性:当method=”post”时,enctype的默认值为application/x-www-form-urlencoded,表⽰使⽤url编码正⽂当method=”get”时,enctype的默认值为null,没有正⽂,所以就不需要enctype了对普通⽂本表单的测试:<form action="${pageContext.request.contextPath }/FileUploadServlet" method="post">⽤户名:<input type="text" name="username"/><br/>⽂件1:<input type="file" name="file1"/><br/>⽂件2:<input type="file" name="file2"/><br/><input type="submit" value="提交"/></form>通过httpWatch测试,查看表单的请求数据正⽂,我们发现请求中只有⽂件名称,⽽没有⽂件内容。

Android使用ftp方式实现文件上传和下载功能

Android使用ftp方式实现文件上传和下载功能

Android使⽤ftp⽅式实现⽂件上传和下载功能近期在⼯作上⼀直再维护平台OTA在线升级项⽬,其中关于这个升级⽂件主要是存放于ftp服务器上的,然后客户端通过⾛ftp 协议⽅式下载⾄本地Android机进⾏⼀个系统升级操作。

那么今天将对ftp实现⽂件上传和下载进⾏⼀个使⽤总结,关于ftp这⽅⾯的理论知识如果不是太了解的各位道友,那么请移步作个具体的了解或者查阅相关资料。

那么先看看个⼈⼯作项⽬这个OTA升级效果图吧。

如下:下⾯是具体的接⼝实现:那么相关ftp的操作,已经被封装到ota.ftp这个包下,各位童鞋可以下载⽰例代码慢慢研究。

另外这个要是⽤ftp服务我们cline端需要再项⽬⼯程导⼊ftp4j-1.7.2.jar包这边作个使⽤的逻辑分析:⾸先在我们的项⽬⼯程FtpApplication中启动这个OtaService,其中OtaService作为⼀个服务运⾏起来,在这个服务⾥⾯拿到封装好ftp相关接⼝的DownLoad.java进⾏ftp⽂件操作,关键代码如下:public void startDownload() {// TODO Auto-generated method stubmDownLoad.start();}public void stopDownload() {mDownLoad.stop();}public void cancel() {mDownLoad.cancel();}public String getOldDate() {return mDownLoad.getDatabaseOldDate();}public String getOldVersion() {return mDownLoad.getDatabaseOldVersion();}public void checkVer(String serverRoot) {// TODO Auto-generated method stubmDownLoad = DownLoad.getInstance();mDownLoad.setServeRoot(serverRoot);mDownLoad.setFtpInfo(mApp.mFtpInfo);mDownLoad.checkUpgrade();}FTPToolkit.javapackage com.asir.ota.ftp;import it.sauronsoftware.ftp4j.FTPClient;import it.sauronsoftware.ftp4j.FTPFile;import java.io.File;import java.util.List;import com.asir.ota.clinet.PathToolkit;import com.asir.ota.ftp.DownLoad.MyFtpListener;/*** FTP客户端⼯具**/public final class FTPToolkit {private FTPToolkit() {}/*** 创建FTP连接** @param host* 主机名或IP* @param port* ftp端⼝* @param username* ftp⽤户名* @param password* ftp密码* @return ⼀个客户端* @throws Exception*/public static FTPClient makeFtpConnection(String host, int port,String username, String password) throws Exception {FTPClient client = new FTPClient();try {client.connect(host, port);if(username != null && password != null) {client.login(username, password);}} catch (Exception e) {throw new Exception(e);}return client;}/*** FTP下载⽂件到本地⼀个⽂件夹,如果本地⽂件夹不存在,则创建必要的⽬录结构 ** @param client* FTP客户端* @param remoteFileName* FTP⽂件* @param localPath* 存的本地⽂件路径或⽬录* @throws Exception*/public static void download(FTPClient client, String remoteFileName,String localPath, long startPoint, MyFtpListener listener) throws Exception {String localfilepath = localPath;int x = isExist(client, remoteFileName);File localFile = new File(localPath);if (localFile.isDirectory()) {if (!localFile.exists())localFile.mkdirs();localfilepath = PathToolkit.formatPath4File(localPath+ File.separator + new File(remoteFileName).getName());}if (x == FTPFile.TYPE_FILE) {try {if (listener != null)client.download(remoteFileName, new File(localfilepath),startPoint, listener);elseclient.download(remoteFileName, new File(localfilepath), startPoint);} catch (Exception e) {throw new Exception(e);}} else {throw new Exception("the target " + remoteFileName + "not exist");}}/*** FTP上传本地⽂件到FTP的⼀个⽬录下** @param client* FTP客户端* @param localfile* 本地⽂件* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void upload(FTPClient client, File localfile,String remoteFolderPath, MyFtpListener listener) throws Exception {remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);try {client.changeDirectory(remoteFolderPath);if (!localfile.exists())throw new Exception("the upload FTP file"+ localfile.getPath() + "not exist!");if (!localfile.isFile())throw new Exception("the upload FTP file"+ localfile.getPath() + "is a folder!");if (listener != null)client.upload(localfile, listener);elseclient.upload(localfile);client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** FTP上传本地⽂件到FTP的⼀个⽬录下** @param client* FTP客户端* @param localfilepath* 本地⽂件路径* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void upload(FTPClient client, String localfilepath,String remoteFolderPath, MyFtpListener listener) throws Exception {File localfile = new File(localfilepath);upload(client, localfile, remoteFolderPath, listener);}/*** 批量上传本地⽂件到FTP指定⽬录上** @param client* FTP客户端* @param localFilePaths* 本地⽂件路径列表* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void uploadListPath(FTPClient client,List<String> localFilePaths, String remoteFolderPath, MyFtpListener listener) throws Exception { remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);try {client.changeDirectory(remoteFolderPath);for (String path : localFilePaths) {File file = new File(path);if (!file.exists())throw new Exception("the upload FTP file" + path + "not exist!");if (!file.isFile())throw new Exception("the upload FTP file" + path+ "is a folder!");if (listener != null)client.upload(file, listener);elseclient.upload(file);}client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** 批量上传本地⽂件到FTP指定⽬录上** @param client* FTP客户端* @param localFiles* 本地⽂件列表* @param remoteFolderPath* FTP上传⽬录* @throws Exception*/public static void uploadListFile(FTPClient client, List<File> localFiles,String remoteFolderPath, MyFtpListener listener) throws Exception {try {client.changeDirectory(remoteFolderPath);remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);for (File file : localFiles) {if (!file.exists())throw new Exception("the upload FTP file" + file.getPath()+ "not exist!");if (!file.isFile())throw new Exception("the upload FTP file" + file.getPath()+ "is a folder!");if (listener != null)client.upload(file, listener);elseclient.upload(file);}client.changeDirectory("/");} catch (Exception e) {throw new Exception(e);}}/*** 判断⼀个FTP路径是否存在,如果存在返回类型(FTPFile.TYPE_DIRECTORY=1、FTPFile.TYPE_FILE=0、 * FTPFile.TYPE_LINK=2) 如果⽂件不存在,则返回⼀个-1** @param client* FTP客户端* @param remotePath* FTP⽂件或⽂件夹路径* @return 存在时候返回类型值(⽂件0,⽂件夹1,连接2),不存在则返回-1*/public static int isExist(FTPClient client, String remotePath) {remotePath = PathToolkit.formatPath4FTP(remotePath);FTPFile[] list = null;try {list = client.list(remotePath);} catch (Exception e) {return -1;}if (list.length > 1)return FTPFile.TYPE_DIRECTORY;else if (list.length == 1) {FTPFile f = list[0];if (f.getType() == FTPFile.TYPE_DIRECTORY)return FTPFile.TYPE_DIRECTORY;// 假设推理判断String _path = remotePath + "/" + f.getName();try {int y = client.list(_path).length;if (y == 1)return FTPFile.TYPE_DIRECTORY;elsereturn FTPFile.TYPE_FILE;} catch (Exception e) {return FTPFile.TYPE_FILE;}} else {try {client.changeDirectory(remotePath);return FTPFile.TYPE_DIRECTORY;} catch (Exception e) {return -1;}}}public static long getFileLength(FTPClient client, String remotePath) throws Exception {String remoteFormatPath = PathToolkit.formatPath4FTP(remotePath);if(isExist(client, remotePath) == 0) {FTPFile[] files = client.list(remoteFormatPath);return files[0].getSize();}else {throw new Exception("get remote file length error!");}}/*** 关闭FTP连接,关闭时候像服务器发送⼀条关闭命令** @param client* FTP客户端* @return 关闭成功,或者链接已断开,或者链接为null时候返回true,通过两次关闭都失败时候返回false*/public static boolean closeConnection(FTPClient client) {if (client == null)return true;if (client.isConnected()) {try {client.disconnect(true);return true;} catch (Exception e) {try {client.disconnect(false);} catch (Exception e1) {e1.printStackTrace();return false;}}}return true;}}包括登录,开始下载,取消下载,获取升级⽂件版本号和服务器版本校验等。

java实现连接ftp服务器并下载文件到本地

java实现连接ftp服务器并下载文件到本地

java实现连接ftp服务器并下载⽂件到本地1.pom.xml引⼊jar包<!--ftp--><dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.6</version></dependency>2.连接ftp服务器⽅法/*** 连接ftp服务器* @param ip ftp地址* @param port 端⼝* @param username 账号* @param password 密码* @return* @throws IOException*/public static FTPClient ftpConnection(String ip,String port, String username, String password) throws IOException {FTPClient ftpClient = new FTPClient();try {ftpClient.connect(ip, Integer.parseInt(port));ftpClient.login(username, password);int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器if(!FTPReply.isPositiveCompletion(replyCode)) {ftpClient.disconnect();logger.error("--ftp连接失败--");System.exit(1);}ftpClient.enterLocalPassiveMode();//这句最好加告诉对⾯服务器开⼀个端⼝ftpClient.setFileType(FTP.BINARY_FILE_TYPE);ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return ftpClient;}3.断开ftp服务⽅法/*** 断开FTP服务器连接* @param ftpClient 初始化的对象* @throws IOException*/public static void close(FTPClient ftpClient) throws IOException{if(ftpClient!=null && ftpClient.isConnected()){ftpClient.logout();ftpClient.disconnect();}}4.下载ftp服务器知道路径的⽂件到本地⽅法/*** 下载ftp服务器⽂件⽅法* @param ftpClient FTPClient对象* @param newFileName 新⽂件名* @param fileName 原⽂件(路径+⽂件名)* @param downUrl 下载路径* @return* @throws IOException*/public static boolean downFile(FTPClient ftpClient, String newFileName, String fileName, String downUrl) throws IOException {boolean isTrue = false;OutputStream os=null;File localFile = new File(downUrl + "/" + newFileName);if (!localFile.getParentFile().exists()){//⽂件夹⽬录不存在创建⽬录localFile.getParentFile().mkdirs();localFile.createNewFile();}os = new FileOutputStream(localFile);isTrue = ftpClient.retrieveFile(new String(fileName.getBytes(),"ISO-8859-1"), os);os.close();return isTrue;}5.调⽤测试mainpublic static void main(String[] args) throws IOException{FTPClient ftpClient = this.ftpConnection("172.*.*.*","*","username","password");boolean flag = downFile(ftpClient,"⽂件名","/路径/+⽂件名","本地路径"); close(ftpClients);System.out.println(flag );//flag=true说明下载成功}。

java连接FTP上传和下载文件

java连接FTP上传和下载文件

package .yxjx.pub;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Properties;import mons.io.FileUtils;import .ftp.FTP;import .ftp.FTPClient;import .ftp.FTPClientConfig;import .ftp.FTPFile;import .ftp.FTPReply;public class FTPHandle {private String username;private String password;private String ip;private int port;private Properties property = null;// 配置private String configFile;// 配置文件的路径名private FTPClient ftpClient = null;private String filedir = "";// FTP文件路径private final String[] FILE_TYPES = { "文件", "目录", "符号链接", "未知类型" };private static SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm");* 设置参数** @param configFile* --参数的配置文件*/private void setArg(String configFile) {property = new Properties();BufferedInputStream inBuff = null;try {inBuff = new BufferedInputStream(this.getClass().getResourceAsStream(configFile));property.load(inBuff);username = property.getProperty("username");password = property.getProperty("password");ip = property.getProperty("ip");port = Integer.parseInt(property.getProperty("port"));filedir = property.getProperty("filedir");} catch (Exception e) {e.printStackTrace();} finally {try {if (inBuff != null)inBuff.close();} catch (Exception e) {e.printStackTrace();}}}/*** 设置FTP客服端的配置--一般可以不设置** @return*/private FTPClientConfig getFtpConfig() {FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);return ftpConfig;}/*** 连接到服务器public void connectServer() {if (ftpClient == null) {int reply;try {setArg(configFile);ftpClient = new FTPClient();// ftpClient.configure(getFtpConfig());ftpClient.connect(ip);ftpClient.login(username, password);ftpClient.setDefaultPort(port);System.out.print(ftpClient.getReplyString());reply = ftpClient.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftpClient.disconnect();System.err.println("FTP server refused connection.");}} catch (Exception e) {System.err.println("登录ftp服务器【" + ip + "】失败");e.printStackTrace();}}}/*** 进入到服务器的某个目录下** @param directory*/public void changeWorkingDirectory() {try {ftpClient.changeWorkingDirectory(filedir);} catch (IOException ioe) {ioe.printStackTrace();}}/*** 上传文件** @param inputStream--文件输入流* @param newFileName--新的文件名*/public void uploadFile(InputStream inputStream, String newFileName) { changeWorkingDirectory();// 进入文件夹// 上传文件BufferedInputStream buffIn = null;try {buffIn = new BufferedInputStream(inputStream);ftpClient.storeFile(newFileName, buffIn);} catch (Exception e) {e.printStackTrace();} finally {try {if (buffIn != null)buffIn.close();} catch (Exception e) {e.printStackTrace();}}}/*** 列出服务器上文件和目录** @param regStr* --匹配的正则表达式*/@SuppressWarnings("unchecked")public List listRemoteFiles(String regStr) {List list = new ArrayList();try {FTPFile[] files = ftpClient.listFiles(regStr);if (files == null || files.length == 0) {System.out.println("There has not any file!");return null;} else {for (FTPFile file : files) {if (file != null) {Map map = new HashMap();String filename = file.getName();int filenamelen = filename.length();if(filenamelen>4){String filetype = filename.substring(filenamelen-3);if("txt".equals(filetype)){String name = file.getName();name = name.substring(0,name.length()-4);map.put("filename", name);map.put("filesize",FileUtils.byteCountToDisplaySize(file.getSize()));map.put("scsj",dateFormat.format(file.getTimestamp().getTime()));list.add(map);}}}}}} catch (Exception e) {e.printStackTrace();}return list;}/*** 下载文件* @param remoteFileName --服务器上的文件名* @param localFileName--本地文件名*/public void loadFile(String remoteFileName,String localFileName){//下载文件BufferedOutputStream buffOut=null;try{buffOut=new BufferedOutputStream(new FileOutputStream(localFileName));ftpClient.retrieveFile(remoteFileName, buffOut);}catch(Exception e){e.printStackTrace();}finally{try{if(buffOut!=null)buffOut.close();}catch(Exception e){e.printStackTrace();}}}/*** 删除文件*/public void deleteFile(String filename){try{ftpClient.deleteFile(filename);}catch(IOException ioe){ioe.printStackTrace();}}/*** 关闭连接*/public void closeConnect(){try{if(ftpClient!=null){ftpClient.logout();ftpClient.disconnect();System.out.println("Ftp have closed");}}catch(Exception e){e.printStackTrace();}}public String getConfigFile() {return configFile;}public void setConfigFile(String configFile) { this.configFile = configFile;}public String[] getFILE_TYPES() {return FILE_TYPES;}public FTPClient getFtpClient() {return ftpClient;}public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getPassword() {return password;}public void setPassword(String password) { this.password = password;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}public Properties getProperty() {return property;}public void setProperty(Properties property) { this.property = property;}public String getUsername() {return username;}public void setUsername(String username) { ername = username;}public String getFiledir() {return filedir;}public void setFiledir(String filedir) {this.filedir = filedir;}}。

ftp文件上传下载命令

ftp文件上传下载命令

ftp⽂件上传下载命令介绍:从本地以⽤户wasqry登录的机器1*.1**.21.67上通过ftp远程登录到ftp服务器上,登录⽤户名是lte****,以下为使⽤该连接做的实验。

查看远程ftp服务器上⽤户lte****相应⽬录下的⽂件所使⽤的命令为:ls,登录到ftp后在ftp命令提⽰符下查看本地机器⽤户wasqry相应⽬录下⽂件的命令是:!ls。

查询ftp命令可在提⽰符下输⼊:?,然后回车。

1、从远程ftp服务器下载⽂件的命令格式:get 远程ftp服务器上当前⽬录下要下载的⽂件名 [下载到本地机器上当前⽬录时的⽂件名],如:get nmap_file [nmap]意思是把远程ftp服务器下的⽂件nmap_file下载到本地机器的当前⽬录下,名称更改为nmap。

带括号表⽰可写可不写,不写的话是以该⽂件名下载。

如果要往ftp服务器上上传⽂件的话需要去修改⼀下vsftpd的配置⽂件,名称是vsftpd.conf,在/etc⽬录下。

要把其中的“#write_enable=YES”前⾯的“#”去掉并保存,然后重启vsftpd服务:sudo service vsftpd restart。

2、向远程ftp服务器上传⽂件的命令格式:put/mput 本地机器上当前⽬录下要上传的⽂件名 [上传到远程ftp服务器上当前⽬录时的⽂件名],如:put/mput sample.c [ftp_sample.c]意思是把本地机器当前⽬录下的⽂件smaple.c上传到远程ftp服务器的当前⽬录下,名称更改为ftp_sample.c。

带括号表⽰可写可不写,不写的话是以该⽂件名上传。

如图下download.sh等⽂件本位于该机器linux系统⽬录,通过如下命令,则将linux系统当前⽬录下的download.sh等⽂件上传⾄ftp服务器的当前⽬录3、最后附上ftp常⽤命令,如下所⽰:FTP>open [ftpservername],和指定的远程Linux FTP服务器连接?FTP>user [username] [password],使⽤指定远程Linux FTP服务器的⽤户登录?FTP>pwd,显⽰远程Linux FTP服务器上的当前路径?FTP>ls,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件?FTP>dir,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件(同上)?FTP>mkdir [foldname],在远程Linux FTP服务器上当前路径下建⽴指定⽬录?FTP>rmdir [foldname],删除远程Linux FTP服务器上当前路径下的指定⽬录?FTP>cd [foldname],更改远程Linux FTP服务器上的⼯作⽬录?FTP>delete [filename],删除远程Linux FTP服务器上指定的⽂件?FTP>rename [filename] [newfilename],重命名远程Linux FTP服务器上指定的⽂件?FTP>close,从远程Linux FTP服务器断开但保留FTP命令参数提⽰?FTP>disconnect,从远程Linux FTP服务器断开但保留FTP命令参数提⽰(同上)?FTP>bye,结束和远程Linux FTP服务器的连接。

Java使用SFTP和FTP两种连接方式实现对服务器的上传下载【我改】

Java使用SFTP和FTP两种连接方式实现对服务器的上传下载【我改】

Java使⽤SFTP和FTP两种连接⽅式实现对服务器的上传下载【我改】【】如何区分是需要使⽤SFTP还是FTP?【】我觉得:1、看是否已知私钥。

SFTP 和 FTP 最主要的区别就是 SFTP 有私钥,也就是在创建连接对象时,SFTP 除了⽤户名和密码外还需要知道私钥 privateKey ,如果有私钥那么就⽤ SFTP,否则就是⽤ FTP。

2、看端⼝号。

如果端⼝号是21,那么就⽤FTP,否则就⽤ SFTP===============转:Java使⽤SFTP和FTP两种连接⽅式实现对服务器的上传下载 <dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version></dependency>2、SFTPUtil⼯具类:import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.util.Properties;import java.util.Vector;import mons.io.IOUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;import com.jcraft.jsch.SftpException;/*** 类说明 sftp⼯具类*/public class SFTPUtil {private transient Logger log = LoggerFactory.getLogger(this.getClass());private ChannelSftp sftp;private Session session;/** SFTP 登录⽤户名*/private String username;/** SFTP 登录密码*/private String password;/** 私钥 */private String privateKey;/** SFTP 服务器地址IP地址*/private String host;/** SFTP 端⼝*/private int port;/*** 构造基于密码认证的sftp对象*/public SFTPUtil(String username, String password, String host, int port) {ername = username;this.password = password;this.host = host;this.port = port;}/*** 构造基于秘钥认证的sftp对象*/public SFTPUtil(String username, String host, int port, String privateKey) {ername = username;this.host = host;this.port = port;this.privateKey = privateKey;}public SFTPUtil(){}/*** 连接sftp服务器*/public void login(){try {JSch jsch = new JSch();if (privateKey != null) {jsch.addIdentity(privateKey);// 设置私钥}session = jsch.getSession(username, host, port);if (password != null) {session.setPassword(password);}Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();Channel channel = session.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;} catch (JSchException e) {e.printStackTrace();}}/*** 关闭连接 server*/public void logout(){if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();}}if (session != null) {if (session.isConnected()) {session.disconnect();}}}/*** 将输⼊流的数据上传到sftp作为⽂件。

java实现文件上传和下载

java实现文件上传和下载

文件上传在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件上传功能。

common-fileupload组件是apache的一个开源项目之一,可以从/commons/fileupload/(/commons/fileupload/)下载。

用该组件可实现一次上传一个或多个文件,并可限制文件大小。

代码下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps你的webappWEB-INFlib下,目录不存在请自建目录。

新建一个servlet: Upload.java用于文件上传:import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;import mons.fileupload.*;public class Upload extends HttpServlet {private String uploadPath = "C:upload"; // 上传文件的目录private String tempPath = "C:uploadtmp"; // 临时文件目录public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{}}在doPost()方法中,当servlet收到浏览器发出的Post请求后,实现文件上传。

以下是示例代码:public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{try {DiskFileUpload fu = new DiskFileUpload();// 设置最大文件尺寸,这里是4MBfu.setSizeMax(4194304);// 设置缓冲区大小,这里是4kbfu.setSizeThreshold(4096);// 设置临时目录:fu.setRepositoryPath(tempPath);// 得到所有的文件:List fileItems = fu.parseRequest(request);Iterator i = fileItems.iterator();// 依次处理每一个文件:while(i.hasNext()) {FileItem fi = (FileItem)i.next();// 获得文件名,这个文件名包括路径:String fileName = fi.getName();// 在这里可以记录用户和文件信息// 写入文件,暂定文件名为a.txt,可以从fileName中提取文件名:fi.write(new File(uploadPath + "a.txt"));}}catch(Exception e) {// 可以跳转出错页面}}如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:public void init() throws ServletException {uploadPath = ....tempPath = ....// 文件夹不存在就自动创建:if(!new File(uploadPath).isDirectory())new File(uploadPath).mkdirs();if(!new File(tempPath).isDirectory())new File(tempPath).mkdirs();}编译该servlet,注意要指定classpath,确保包含commons-upload-1.0.jar和tomcatcommonlibservlet-api.jar。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用Java实现FTP批量大文件上传下载(一)本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量、大文件的上传下载控件。

文章在比较了一系列FTP客户库的基础上,就其中一个比较通用且功能较强的j-ftp类库,对一些比较常见的功能如进度条、断点续传、内外网的映射、在Applet中回调JavaScript函数等问题进行详细的阐述及代码实现,希望通过此文起到一个抛砖引玉的作用。

一、引子笔者在实施一个项目过程中出现了一种基于Web的文件上传下载需求。

在全省(或全国)各地的用户,需要将一些文件上传至某中心的文件服务器上。

这些文件是用于一些大型的工程建设,可能涉及到上千万甚至上亿的建设工程。

文件具有三个鲜明的特征:一是文件大,可能达到50M;二是文件数量多,有可能15个左右;三是数据安全性方面要求数字签名及数据加密。

首先考虑到是基于HTTP的传输方式。

但笔者通过比较很快发现满足上面的需求:1:用HTTP协议上传,似乎更适合web编程的方便性;上传小于1M文件速度要比用FTP协议上传文件略快。

但对于批量及大文件的传输可能无能为力。

当然,它也有它的优势,如不像FTP那样,必须在服务器端启动一个FTP服务。

2:用FTP协议上传文件大于1M的文件速度比HTTP快。

文件越大,上传的速度就比HTTP上传的速度快数倍。

而且用java编写程序;FTP比HTTP方便。

笔者曾经使用VB也写过ActiveX控件来进行批量文件的上传下载,其功能也很强大。

只是由于没有对CAB文件或OCX进行专门的数字签名,因此需要进行客户端烦琐的设置,如设置安全站点、降低客户端的安全级别等等,因而放弃了些方案。

同时考虑到在需在客户端对文件进行数字签名及数据加密,决定采用Applet 的方式实现。

文件上传之前,在客户端可以获取本地USBKEY密钥信息,完成对上传文件的加密和签名处理。

虽然采用Applet要求在客户端安装JRE运行时环境,给客户端的管理及使用带来一度的不方便性,但是相对起如此大量的文件及文件的安全性,这也许已经算是比较小的代价了。

总结一下运行的环境为:FTP服务器端:Serv-U,专业的FTP服务器端程序,网上有现成的软件下载,当然读者也可能自己写一个服务器端的FTP文件接收程序来进行解释。

如果没有特殊要求或功能的话,Serv-U应该可以满足我们一般上传下载的需求了;客户端:Java applet,当年让Java大火了一把的号称与微软的ActiveX相提并论的技术当然,现在Java出了JavaFX,是不是Applet的替代品呢?应用环境:Internet网,最终目的。

二、Java FTP客户端库的选择让我们设想这样一个情形--我们想写一个纯Java的从一个远程计算机上运行的FTP服务器上传下载文件的应用程序;我们还希望能够得到那些供下载的远程文件的基本文件信息,如文件名、数据或者文件大小等。

尽管从头开始写一个FTP协议处理程序是可能的,并且也许很有趣,但这项工作也是困难、漫长并且存在着潜在的危险。

因为我们不愿意亲自花时间、精力、或者金钱去写这样的一个处理程序,所以我们转而采用那些已经存在的可重用的组件。

并且很多的库存在于网上。

找一个优秀的适合我们需要的Java FTP 客户端库并不像看起来那么简单。

相反这是一项非常痛苦复杂的工作。

首先找到一个FTP客户端库需要一些时间,其次,在我们找到所有的存在的库后,我们该选哪一个呢?每个库都适合不同的需求。

这些库在性能上是不等价的,并且它们的设计上有着根本上的差别。

每个类库都各具特点并使用不同的术语来描述它们。

因而,评价和比较FTP客户端库是一件困难的事情。

使用可重用组件是一种值得提倡的方法,但是在这种情况下,刚开始往往是令人气馁的。

后来或许有点惭愧:在选择了一个好的FTP库后,其后的工作就非常简单了,按简单的规则来就行了。

目前,已经有很多公开免费的ftp客户端类库,如simpleftp、J-ftp等,还有很多其他的ftpclient。

如下表所示,表中未能全部列出,如读者有更好的客户端FTP类库,请进行进一步的补充。

在本文中,笔者采用是J-ftp。

这个是个开源的且功能十分强大的客户端FTP 类库。

笔者很喜欢,同时也向各位读者推荐一下。

算了免费为它做一个广告。

三、基本功能1、登陆采用FTP进行文件传输,其实本质上还是采用.socket进行通信。

以下代码只是类.FtpConnection其中一个login方法。

当然在下面的代码,为了节省版面,以及将一些原理阐述清楚,笔者将一些没必要的代码去掉了,如日志等代码。

完整的代码请参考J-ftp的源代码或是笔者所以的示例源代码,后面的代码示例也同理:public int login(String username, String password){ername = username;this.password = password;int status = LOGIN_OK;jcon =new JConnection(host, port);if(jcon.isThere()){in = jcon.getReader();if(getLine(POSITIVE) == null)//FTP220_SERVICE_READY) == null){ok =false;status = OFFLINE;}if(!getLine(loginAck).startsWith(POSITIVE))//FTP230_LOGGED_IN)){if(success(POSITIVE))//FTP230_LOGGED_IN)){}else{ok =false;status = WRONG_LOGIN_DATA;}}}else{if(m sg){Log.debug("FTP not available!");ok =false;status = GENERIC_FAILED;}}if(ok){connected =true;system();binary();String[] advSettings =new String[6];if(getOsType().indexOf("OS/2") >= 0){LIST_DEFAULT = "LIST";}if(LIST.equals("default")){//just get the first item (somehow it knows first is the//FTP list command)advSettings = LoadSet.loadSet(Settings.adv_settings);//*** IF FILE NOT FOUND, CREATE IT AND SET IT TO LIST_DEFAULTif(advSettings == null){LIST = LIST_DEFAULT;SaveSet s =new SaveSet(Settings.adv_settings, LIST);}else{LIST = advSettings[0];if(LIST == null){LIST = LIST_DEFAULT;}}}if(getOsType().indexOf("MVS") >= 0){LIST = "LIST";}//***fireDirectoryUpdate(this);fireConnectionInitialized(this);}else{fireConnectionFailed(this, new Integer(status).toString());}return status;}此登陆方法中,有一个JConnection类,此类负责建立socket套接字,同时,此类是一种单独的线程,这样的好处是为了配合界面的变化,而将网络的套接字连接等工作做为单独的线程来处理,有利于界面的友好性。

下面是.JConnection类的run方法,当然,此线程的启动是在JConnection类的构造方法中启动的。

public void run(){try{s =new Socket(host, port);localPort = s.getLocalPort();//if(tim e > 0) s.setSoTim eout(tim e);out =new PrintStream(new BufferedOutputStream(s.getOutputStream (),Settings.bufferSize));in =new BufferedReader(new InputStreamReader(s.getInputStream()),Settings.bufferSize);isOk = true;// }}catch(Exception ex){ex.printStackTrace();Log.out("WARNING: connection closed due to exception (" + host +":" + port + ")");isOk = false;try{if((s !=null) && !s.isClosed()){s.close();}if(out !=null){out.close();}if(in !=null){in.close();}}catch(Exception ex2){ex2.printStackTrace();Log.out("WARNING: got m ore errors trying to close socket and strea ms");}}established =true;}此run方法中的socket这里说明一下,此类实现客户端套接字(也可以就叫“套接字”),套接字是两台机器之间的通信端点。

套接字的实际工作由 SocketImpl 类的实例执行。

应用程序通过更改创建套接字实现的套接字工厂可以配置它自身,以创建适合本地防火墙的套接字。

具体的说明请参考JDK5 的API说明,最好是中文的。

呵呵。

用Java实现FTP批量大文件上传下载(二)上传下载文件的上传可以分成多线程及单线程,在单线程情况下比较简单,而在多线程的情况下,要处理的事情要多点,同时也要小心很多。

下面是net.sf.jft .FtpConnection的上传handleUpload方法。

相关文档
最新文档