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);//单位:字节。

ftp文件操作类(上传、下载、删除、创建、重命名、获取目录中的所有文件)

ftp文件操作类(上传、下载、删除、创建、重命名、获取目录中的所有文件)

ftp⽂件操作类(上传、下载、删除、创建、重命名、获取⽬录中的所有⽂件)ftp⽂件操作类1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using ;6using System.IO;7using System.Data;8using ponentModel;9using System.Windows.Forms;10using System.Text.RegularExpressions;11using System.Globalization;12using System.Collections;1314namespace ESIMRobot15 {16#region⽂件信息结构17public struct FileStruct18 {19public string Flags;20public string Owner;21public string Group;22public bool IsDirectory;23public DateTime CreateTime;24public string Name;25 }26public enum FileListStyle27 {28 UnixStyle,29 WindowsStyle,30 Unknown31 }32#endregion3334///<summary>35/// ftp⽂件上传、下载操作类36///</summary>37public class FTPHelper38 {39private string ftpServerURL;40private string ftpUser;41private string ftpPassWord;4243///<summary>44///45///</summary>46///<param name="ftpServerURL">ftp服务器路径</param>47///<param name="ftpUser">ftp⽤户名</param>48///<param name="ftpPassWord">ftp⽤户名</param>49public FTPHelper(string ftpServerURL, string ftpUser, string ftpPassWord)50 {51this.ftpServerURL = ftpServerURL;52this.ftpUser = ftpUser;53this.ftpPassWord = ftpPassWord;54 }55///<summary>56///通过⽤户名,密码连接到FTP服务器57///</summary>58///<param name="ftpUser">ftp⽤户名,匿名为“”</param>59///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>60public FTPHelper(string ftpUser, string ftpPassWord)61 {62this.ftpUser = ftpUser;63this.ftpPassWord = ftpPassWord;64 }6566///<summary>67///匿名访问68///</summary>69public FTPHelper(string ftpURL)70 {71this.ftpUser = "";72this.ftpPassWord = "";73 }747576//**************************************************** Start_1 *********************************************************//77///<summary>78///从FTP下载⽂件到本地服务器,⽀持断点下载79///</summary>80///<param name="ftpFilePath">ftp⽂件路径,如"ftp://localhost/test.txt"</param>81///<param name="saveFilePath">保存⽂件的路径,如C:\\test.txt</param>82public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath)83 {84 System.IO.FileStream fs = null;85 .FtpWebResponse ftpRes = null;86 System.IO.Stream resStrm = null;87try88 {89//下载⽂件的URI90 Uri uri = new Uri(ftpFilePath);91//设定下载⽂件的保存路径92string downFile = saveFilePath;9394//FtpWebRequest的作成95 .FtpWebRequest ftpReq = (.FtpWebRequest)96 .WebRequest.Create(uri);97//设定⽤户名和密码98 ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);99//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定100 ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;101//要求终了后关闭连接102 ftpReq.KeepAlive = false;103//使⽤ASCII⽅式传送104 eBinary = false;105//设定PASSIVE⽅式⽆效106 ePassive = false;107108//判断是否继续下载109//继续写⼊下载⽂件的FileStream110if (System.IO.File.Exists(downFile))111 {112//继续下载113 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;114 fs = new System.IO.FileStream(115 downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);116 }117else118 {119//⼀般下载120 fs = new System.IO.FileStream(121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);122 }123124//取得FtpWebResponse125 ftpRes = (.FtpWebResponse)ftpReq.GetResponse();126//为了下载⽂件取得Stream127 resStrm = ftpRes.GetResponseStream();128//写⼊下载的数据129byte[] buffer = new byte[1024];130while (true)131 {132int readSize = resStrm.Read(buffer, 0, buffer.Length);133if (readSize == 0)134break;135 fs.Write(buffer, 0, readSize);136 }137 }138catch (Exception ex)139 {140throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 141 }142finally143 {144 fs.Close();145 resStrm.Close();146 ftpRes.Close();147 }148 }149150151#region152//从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹函数列表153154///<summary>155///从ftp下载⽂件到本地服务器156///</summary>157///<param name="ftpFilePath">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>158///<param name="saveFilePath">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>159public void DownLoadFile(string ftpFilePath, string saveFilePath)160 {161 Stream responseStream = null;162 FileStream fileStream = null;163 StreamReader reader = null;164try165 {166// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";167 FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath);168 downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;169 downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);170 FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();171 responseStream = downloadResponse.GetResponseStream();172173 fileStream = File.Create(saveFilePath);174byte[] buffer = new byte[1024];175int bytesRead;176while (true)177 {178 bytesRead = responseStream.Read(buffer, 0, buffer.Length);179if (bytesRead == 0)180break;181 fileStream.Write(buffer, 0, bytesRead);182 }183 }184catch (Exception ex)185 {186throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 187 }188finally189 {190if (reader != null)191 {192 reader.Close();193 }194if (responseStream != null)195 {196 responseStream.Close();197 }198if (fileStream != null)199 {200 fileStream.Close();201 }202 }203 }204205206///<summary>207///列出当前⽬录下的所有⽂件和⽬录208///</summary>209///<param name="ftpDirPath">FTP⽬录</param>210///<returns></returns>211public List<FileStruct> ListCurrentDirFilesAndChildDirs(string ftpDirPath)212 {213 WebResponse webresp = null;214 StreamReader ftpFileListReader = null;215 FtpWebRequest ftpRequest = null;216try217 {218 ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirPath));219 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;220 ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);221 webresp = ftpRequest.GetResponse();222 ftpFileListReader = new StreamReader(webresp.GetResponseStream(),Encoding.GetEncoding("UTF-8")); 223 }224catch (Exception ex)225 {226throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());227 }228string Datastring = ftpFileListReader.ReadToEnd();229return GetListX(Datastring);230231 }232233///<summary>234///列出当前⽬录下的所有⽂件235///</summary>236///<param name="ftpDirPath">FTP⽬录</param>237///<returns></returns>238public List<FileStruct> ListCurrentDirFiles(string ftpDirPath)239 {240 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirPath);241 List<FileStruct> listFile = new List<FileStruct>();242foreach (FileStruct file in listAll)243 {244if (!file.IsDirectory)245 {246 listFile.Add(file);247 }248 }249return listFile;250 }251252253///<summary>254///列出当前⽬录下的所有⼦⽬录255///</summary>256///<param name="ftpDirath">FRTP⽬录</param>257///<returns>⽬录列表</returns>258public List<FileStruct> ListCurrentDirChildDirs(string ftpDirath)259 {260 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirath);261 List<FileStruct> listDirectory = new List<FileStruct>();262foreach (FileStruct file in listAll)263 {264if (file.IsDirectory)265 {266 listDirectory.Add(file);267 }268 }269return listDirectory;270 }271272273///<summary>274///获得⽂件和⽬录列表(返回类型为: List<FileStruct> )275///</summary>276///<param name="datastring">FTP返回的列表字符信息</param>277private List<FileStruct> GetListX(string datastring)278 {279 List<FileStruct> myListArray = new List<FileStruct>();280string[] dataRecords = datastring.Split('\n');281 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);282foreach (string s in dataRecords)283 {284if (_directoryListStyle != FileListStyle.Unknown && s != "")285 {286 FileStruct f = new FileStruct();287 = "..";288switch (_directoryListStyle)289 {290case FileListStyle.UnixStyle:291 f = ParseFileStructFromUnixStyleRecord(s);292break;293case FileListStyle.WindowsStyle:294 f = ParseFileStructFromWindowsStyleRecord(s);295break;296 }297if (!( == "." || == ".."))298 {299 myListArray.Add(f);300 }301 }302 }303return myListArray;304 }305///<summary>306///从Unix格式中返回⽂件信息307///</summary>308///<param name="Record">⽂件信息</param>309private FileStruct ParseFileStructFromUnixStyleRecord(string Record)310 {311 FileStruct f = new FileStruct();312string processstr = Record.Trim();313 f.Flags = processstr.Substring(0, 10);314 f.IsDirectory = (f.Flags[0] == 'd');315 processstr = (processstr.Substring(11)).Trim();316 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分317 f.Owner = cutSubstringFromStringWithTrim(ref processstr, '', 0);318 f.Group = cutSubstringFromStringWithTrim(ref processstr, '', 0);319 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分320string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2]; 321if (yearOrTime.IndexOf(":") >= 0) //time322 {323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());324 }325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, '', 8));326 = processstr; //最后就是名称327return f;328 }329330///<summary>331///从Windows格式中返回⽂件信息332///</summary>333///<param name="Record">⽂件信息</param>334private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)335 {336 FileStruct f = new FileStruct();337string processstr = Record.Trim();338string dateStr = processstr.Substring(0, 8);339 processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();340string timeStr = processstr.Substring(0, 7);341 processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();342 DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;343 myDTFI.ShortTimePattern = "t";344 f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);345if (processstr.Substring(0, 5) == "<DIR>")346 {347 f.IsDirectory = true;348 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();349 }350else351 {352string[] strs = processstr.Split(new char[] { '' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1];354 f.IsDirectory = false;355 }356 = processstr;357return f;358 }359360361///<summary>362///按照⼀定的规则进⾏字符串截取363///</summary>364///<param name="s">截取的字符串</param>365///<param name="c">查找的字符</param>366///<param name="startIndex">查找的位置</param>367private string cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)368 {369int pos1 = s.IndexOf(c, startIndex);370string retString = s.Substring(0, pos1);371 s = (s.Substring(pos1)).Trim();372return retString;373 }374375376///<summary>377///判断⽂件列表的⽅式Window⽅式还是Unix⽅式378///</summary>379///<param name="recordList">⽂件信息列表</param>380private FileListStyle GuessFileListStyle(string[] recordList)381 {382foreach (string s in recordList)383 {384if (s.Length > 10385 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))386 {387return FileListStyle.UnixStyle;388 }389else if (s.Length > 8390 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))391 {392return FileListStyle.WindowsStyle;393 }394 }395return FileListStyle.Unknown;396 }397398399///<summary>400///从FTP下载整个⽂件夹401///</summary>402///<param name="ftpDirPath">FTP⽂件夹路径</param>403///<param name="saveDirPath">保存的本地⽂件夹路径</param>404///调⽤实例: DownFtpDir("FTP://192.168.1.113/WangJin", @"C:\QMDownload\SoftMgr");405///当调⽤的时候先判断saveDirPath的⼦⽬录中是否有WangJin⽬录,有则执⾏,没有创建后执⾏406///最终⽂件保存在@"C:\QMDownload\SoftMgr\WangJin"下407public bool DownFtpDir(string ftpDirPath, string saveDirPath)408 {409bool success = true;410try411 {412 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);413if (!Directory.Exists(saveDirPath))414 {415 Directory.CreateDirectory(saveDirPath);416 }417foreach (FileStruct f in files)418 {419if (f.IsDirectory) //⽂件夹,递归查询421 DownFtpDir(ftpDirPath + "/" + , saveDirPath + "\\" + );422 }423else//⽂件,直接下载424 {425 DownLoadFile(ftpDirPath + "/" + , saveDirPath + "\\" + );426 }427 }428 }429catch (Exception e)430 {431 MessageBox.Show(e.Message);432 success = false;433 }434return success;435 }436#endregion437438439440///<summary>441///列出当前⽬录下的所有⼦⽬录和⽂件到TreeView控件中442///</summary>443///<param name="ftpDirPath"> FTP服务器⽬录</param>444///<param name="treeview">显⽰到TreeView控件中</param>445///<param name="treenode">TreeView控件的⼦节点</param>446public void ListCurrentDirFilesAndDirToTreeView(string ftpDirPath, TreeView treeview, TreeNode treenode) 447 {448if (ftpDirPath == "")449 {450 ftpDirPath = ftpServerURL;451 }452if (treeview != null)453 {454 treeview.Nodes.Clear();455 treenode = treeview.Nodes.Add(ftpDirPath);456 }457 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);458foreach (FileStruct f in files)459 {460if (f.IsDirectory) //如果为⽬录(⽂件夹),递归调⽤461 {462 TreeNode td = treenode.Nodes.Add();463 ListCurrentDirFilesAndDirToTreeView(ftpDirPath + "/" + , null, td);464 }465else//如果为⽂件,直接加⼊到节点中466 {467 treenode.Nodes.Add();468 }469 }470 }471//************************************* End_1 ****************************//472473474475476//************************************ Start_2 ***************************//477///<summary>478///检测⽂件或⽂件⽬录是否存在479///</summary>480///<param name="ftpDirPath">ftp服务器中的⽬录路径</param>481///<param name="ftpDirORFileName">待检测的⽂件或⽂件名</param>482///<returns></returns>483///操作实例: ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/Record/", "")484/// ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/RecordFile/", "333.txt")485public bool fileOrDirCheckExist(string ftpDirPath, string ftpDirORFileName)486 {487bool success = true;488 FtpWebRequest ftpWebRequest = null;489 WebResponse webResponse = null;490 StreamReader reader = null;491try492 {493string url = ftpDirPath + ftpDirORFileName;494 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));495 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);496 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;497 ftpWebRequest.KeepAlive = false;498 webResponse = ftpWebRequest.GetResponse();499 reader = new StreamReader(webResponse.GetResponseStream());500string line = reader.ReadLine();501while (line != null)502 {503if (line == ftpDirORFileName)504 {505break;507 line = reader.ReadLine();508 }509 }510catch (Exception)511 {512 success = false;513 }514finally515 {516if (reader != null)517 {518 reader.Close();519 }520if (webResponse != null)521 {522 webResponse.Close();523 }524 }525return success;526 }527528529///<summary>530///获得⽂件和⽬录列表(返回类型为:FileStruct)531///</summary>532///<param name="datastring">FTP返回的列表字符信息</param>533public FileStruct GetList(string datastring)534 {535 FileStruct f = new FileStruct();536string[] dataRecords = datastring.Split('\n');537 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);538if (_directoryListStyle != FileListStyle.Unknown && datastring != "")539 {540541switch (_directoryListStyle)542 {543case FileListStyle.UnixStyle:544 f = ParseFileStructFromUnixStyleRecord(datastring);545break;546case FileListStyle.WindowsStyle:547 f = ParseFileStructFromWindowsStyleRecord(datastring);548break;549 }550 }551return f;552 }553554555///<summary>556///上传557///</summary>558///<param name="localFilePath">本地⽂件名路径</param>559///<param name="ftpDirPath">上传到ftp中⽬录的路径</param>560///<param name="ftpFileName">上传到ftp中⽬录的⽂件名</param>561///<param name="fileLength">限制上传⽂件的⼤⼩(Bytes为单位)</param>562///操作实例: ftpclient.fileUpload(@"E:\bin\Debug\Web\RecordFile\wangjin\wangjin.txt", "FTP://192.168.1.113/Record/","123.txt",0 );563public bool UploadFile(FileInfo localFilePath, string ftpDirPath, string ftpFileName, long fileLength)564 {565bool success = true;566long filesize = 0;567 FtpWebRequest ftpWebRequest = null;568 FileStream localFileStream = null;569 Stream requestStream = null;570if (fileLength > 0)571 {572 filesize = fileLength * 1024 * 1024;573 }574if (localFilePath.Length <= filesize || filesize == 0)575 {576if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 577 {578try579 {580string uri = ftpDirPath + ftpFileName;581 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));582 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);583 eBinary = true;584 ftpWebRequest.KeepAlive = false;585 ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;586 ftpWebRequest.ContentLength = localFilePath.Length;587int buffLength = 2048; //定义缓存⼤⼩2KB588byte[] buff = new byte[buffLength];589int contentLen;590 localFileStream = localFilePath.OpenRead();591 requestStream = ftpWebRequest.GetRequestStream();592 contentLen = localFileStream.Read(buff, 0, buffLength);593while (contentLen != 0)594 {595 requestStream.Write(buff, 0, contentLen);596 contentLen = localFileStream.Read(buff, 0, buffLength);597 }598 }599catch (Exception)600 {601 success = false;602 }603finally604 {605if (requestStream != null)606 {607 requestStream.Close();608 }609if (localFileStream != null)610 {611 localFileStream.Close();612 }613 }614 }615else616 {617 success = false;618 MessageBox.Show("FTP⽂件路径不存在!");619 }620 }621else622 {623 success = false;624 MessageBox.Show("⽂件⼤⼩超过设置范围!" + "\n" + "⽂件实际⼤⼩为:" + localFilePath.Length + "\n" + "允许上传阈值为:" + (5 * 1024 * 1024).ToString()); 625 }626return success;627 }628629///<summary>630///下载⽂件631///</summary>632///<param name="ftpFilePath">需要下载的⽂件名路径</param>633///<param name="localFilePath">本地保存的⽂件名路径)</param>634///操作实例: ftpclient.fileDownload(@"E:\bin\Debug\Web\RecordFile\wangjin\459.txt", "FTP://192.168.1.113/Record/123.txt");635public bool DownloadFile( string localFilePath, string ftpFilePath)636 {637bool success = true;638 FtpWebRequest ftpWebRequest = null;639 FtpWebResponse ftpWebResponse = null;640 Stream ftpResponseStream = null;641 FileStream outputStream = null;642try643 {644 outputStream = new FileStream(localFilePath, FileMode.Create);645string uri = ftpFilePath;646 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));647 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);648 eBinary = true;649 ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;650 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();651 ftpResponseStream = ftpWebResponse.GetResponseStream();652long contentLength = ftpWebResponse.ContentLength;653int bufferSize = 2048;654byte[] buffer = new byte[bufferSize];655int readCount;656 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);657while (readCount > 0)658 {659 outputStream.Write(buffer, 0, readCount);660 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);661 }662 }663catch (Exception)664 {665 success = false;666 }667finally668 {669if (outputStream != null)670 {671 outputStream.Close();672 }673if (ftpResponseStream != null)674 {675 ftpResponseStream.Close();676 }677if (ftpWebResponse != null)679 ftpWebResponse.Close();680 }681 }682return success;683 }684685686///<summary>687///重命名688///</summary>689///<param name="ftpDirPath">ftp服务器中的⽬录</param>690///<param name="currentFilename">当前要修改的⽂件名</param>691///<param name="newFilename">修改后的新⽂件名</param>692///操作实例: ftpclientxy.fileRename("FTP://192.168.1.113/RecordFile/", "123.txt", "333.txt");693public bool RenameFile(string ftpDirPath, string currentFileName, string newFileName)694 {695bool success = true;696 FtpWebRequest ftpWebRequest = null;697 FtpWebResponse ftpWebResponse = null;698 Stream ftpResponseStream = null;699if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 700 {701try702 {703string uri = ftpDirPath + currentFileName;704 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));705 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);706 eBinary = true;707 ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;708 ftpWebRequest.RenameTo = newFileName;709 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();710 ftpResponseStream = ftpWebResponse.GetResponseStream();711 }712catch (Exception)713 {714 success = false;715 }716finally717 {718if (ftpResponseStream != null)719 {720 ftpResponseStream.Close();721 }722if (ftpWebResponse != null)723 {724 ftpWebResponse.Close();725 }726 }727 }728else729 {730 success = false;731 MessageBox.Show("FTP⽂件路径不存在!");732 }733return success;734 }735736///<summary>737///在⽬录下创建⼦⽬录738///</summary>739///<param name="ftpDirPath">ftp服务器中的⽬录</param>740///<param name="ftpFileDir">待创建的⼦⽬录</param>741///<returns></returns>742///操作实例: ftpclient.fileDirMake("FTP://192.168.1.113/RecordFile/", "WangJinFile")743public bool MakeDir(string ftpDirPath, string ftpFileDir)744 {745bool success = true;746 FtpWebRequest ftpWebRequest = null;747 WebResponse webResponse = null;748 StreamReader reader = null;749try750 {751string url = ftpDirPath + ftpFileDir;752 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));753// 指定数据传输类型754 eBinary = true;755 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);756 ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;757 webResponse = ftpWebRequest.GetResponse();758 }759catch (Exception)760 {761 success = false;762 }763finally765if (reader != null)766 {767 reader.Close();768 }769if (webResponse != null)770 {771 webResponse.Close();772 }773 }774return success;775 }776777778///<summary>779///删除⽬录中的⽂件780///</summary>781///<param name="ftpDirPath"></param>782///<param name="ftpFileName"></param>783///<returns></returns>784///操作实例: ftpclient.fileDelete("FTP://192.168.1.113/RecordFile/WangJinFile/", "333.txt")785public bool DeleteFile(string ftpDirPath, string ftpFileName)786 {787bool success = true;788 FtpWebRequest ftpWebRequest = null;789 FtpWebResponse ftpWebResponse = null;790 Stream ftpResponseStream = null;791 StreamReader streamReader = null;792try793 {794string uri = ftpDirPath + ftpFileName;795 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));796 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);797 ftpWebRequest.KeepAlive = false;798 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;799 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();800long size = ftpWebResponse.ContentLength;801 ftpResponseStream = ftpWebResponse.GetResponseStream();802 streamReader = new StreamReader(ftpResponseStream);803string result = String.Empty;804 result = streamReader.ReadToEnd();805 }806catch (Exception)807 {808 success = false;809 }810finally811 {812if (streamReader != null)813 {814 streamReader.Close();815 }816if (ftpResponseStream != null)817 {818 ftpResponseStream.Close();819 }820if (ftpWebResponse != null)821 {822 ftpWebResponse.Close();823 }824 }825return success;826 }827828///<summary>829///获取⽬录的⼦⽬录数组830///</summary>831///<param name="ftpDirPath"></param>832///<returns></returns>833///操作实例: string []filedir = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 834public string[] GetDirArray(string ftpDirPath)835 {836string[] deleteFolders;837 FtpWebRequest ftpWebRequest = null;838 FtpWebResponse ftpWebResponse = null;839 Stream ftpResponseStream = null;840 StreamReader streamReader = null;841 StringBuilder result = new StringBuilder();842try843 {844 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath));845 eBinary = true;846 ePassive = false;847 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);848 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;849 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();。

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

JAVASFTP文件上传、下载及批量下载实例

JAVASFTP文件上传、下载及批量下载实例

JAVASFTP⽂件上传、下载及批量下载实例1.jsch官⽅API查看地址(附件为需要的jar)2.jsch简介JSch(Java Secure Channel)是⼀个SSH2的纯Java实现。

它允许你连接到⼀个SSH服务器,并且可以使⽤端⼝转发,X11转发,⽂件传输等,当然你也可以集成它的功能到你⾃⼰的应⽤程序。

SFTP(Secure File Transfer Protocol)安全⽂件传送协议。

可以为传输⽂件提供⼀种安全的加密⽅法。

SFTP 为 SSH的⼀部份,是⼀种传输⽂件到服务器的安全⽅式,但是传输效率⽐普通的FTP要低。

3.api常⽤的⽅法:put():⽂件上传get():⽂件下载cd():进⼊指定⽬录ls():得到指定⽬录下的⽂件列表rename():重命名指定⽂件或⽬录rm():删除指定⽂件mkdir():创建⽬录rmdir():删除⽬录put和get都有多个重载⽅法,⾃⼰看源代码4.对常⽤⽅法的使⽤,封装成⼀个util类import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Properties;import java.util.Vector;import org.apache.log4j.Logger;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;import com.jcraft.jsch.SftpATTRS;import com.jcraft.jsch.SftpException;import com.jcraft.jsch.ChannelSftp.LsEntry;/*** sftp⼯具类** @author xxx* @date 2014-6-17* @time 下午1:39:44* @version 1.0*/public class SFTPUtils{private static Logger log = Logger.getLogger(SFTPUtils.class.getName());private String host;//服务器连接ipprivate String username;//⽤户名private String password;//密码private int port = 22;//端⼝号private ChannelSftp sftp = null;private Session sshSession = null;public SFTPUtils(){}public SFTPUtils(String host, int port, String username, String password){this.host = host;public SFTPUtils(String host, String username, String password) {this.host = host;ername = username;this.password = password;}/*** 通过SFTP连接服务器*/public void connect(){try{JSch jsch = new JSch();jsch.getSession(username, host, port);sshSession = jsch.getSession(username, host, port);if (log.isInfoEnabled()){("Session created.");}sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();if (log.isInfoEnabled()){("Session connected.");}Channel channel = sshSession.openChannel("sftp");channel.connect();if (log.isInfoEnabled()){("Opening Channel.");}sftp = (ChannelSftp) channel;if (log.isInfoEnabled()){("Connected to " + host + ".");}}catch (Exception e){e.printStackTrace();}}/*** 关闭连接*/public void disconnect(){if (this.sftp != null){if (this.sftp.isConnected()){this.sftp.disconnect();if (log.isInfoEnabled()){("sftp is closed already");}}}if (this.sshSession != null){if (this.sshSession.isConnected()){this.sshSession.disconnect();if (log.isInfoEnabled()){("sshSession is closed already");}/*** 批量下载⽂件* @param remotPath:远程下载⽬录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/) * @param localPath:本地保存⽬录(以路径符号结束,D:\Duansha\sftp\)* @param fileFormat:下载⽂件格式(以特定字符开头,为空不做检验)* @param fileEndFormat:下载⽂件格式(⽂件格式)* @param del:下载后是否删除sftp⽂件* @return*/public List<String> batchDownLoadFile(String remotePath, String localPath,String fileFormat, String fileEndFormat, boolean del){List<String> filenames = new ArrayList<String>();try{// connect();Vector v = listFiles(remotePath);// sftp.cd(remotePath);if (v.size() > 0){System.out.println("本次处理⽂件个数不为零,开始下载...fileSize=" + v.size());Iterator it = v.iterator();while (it.hasNext()){LsEntry entry = (LsEntry) it.next();String filename = entry.getFilename();SftpATTRS attrs = entry.getAttrs();if (!attrs.isDir()){boolean flag = false;String localFileName = localPath + filename;fileFormat = fileFormat == null ? "" : fileFormat.trim();fileEndFormat = fileEndFormat == null ? "": fileEndFormat.trim();// 三种情况if (fileFormat.length() > 0 && fileEndFormat.length() > 0){if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)){flag = downloadFile(remotePath, filename,localPath, filename);if (flag){filenames.add(localFileName);if (flag && del){deleteSFTP(remotePath, filename);}}}}else if (fileFormat.length() > 0 && "".equals(fileEndFormat)){if (filename.startsWith(fileFormat)){flag = downloadFile(remotePath, filename, localPath, filename);if (flag){filenames.add(localFileName);if (flag && del){deleteSFTP(remotePath, filename);}}}}else if (fileEndFormat.length() > 0 && "".equals(fileFormat)){if (filename.endsWith(fileEndFormat)){flag = downloadFile(remotePath, filename,localPath, filename);filenames.add(localFileName);if (flag && del){deleteSFTP(remotePath, filename);}}}}else{flag = downloadFile(remotePath, filename,localPath, filename);if (flag){filenames.add(localFileName);if (flag && del){deleteSFTP(remotePath, filename);}}}}}}if (log.isInfoEnabled()){("download file is success:remotePath=" + remotePath+ "and localPath=" + localPath + ",file size is"+ v.size());}}catch (SftpException e){e.printStackTrace();}finally{// this.disconnect();}return filenames;}/*** 下载单个⽂件* @param remotPath:远程下载⽬录(以路径符号结束)* @param remoteFileName:下载⽂件名* @param localPath:本地保存⽬录(以路径符号结束)* @param localFileName:保存⽂件名* @return*/public boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName) {FileOutputStream fieloutput = null;try{// sftp.cd(remotePath);File file = new File(localPath + localFileName);// mkdirs(localPath + localFileName);fieloutput = new FileOutputStream(file);sftp.get(remotePath + remoteFileName, fieloutput);if (log.isInfoEnabled()){("===DownloadFile:" + remoteFileName + " success from sftp.");}return true;}catch (FileNotFoundException e){e.printStackTrace();}catch (SftpException e){e.printStackTrace();}finally{try{fieloutput.close();}catch (IOException e){e.printStackTrace();}}}return false;}/*** 上传单个⽂件* @param remotePath:远程保存⽬录* @param remoteFileName:保存⽂件名* @param localPath:本地上传⽬录(以路径符号结束)* @param localFileName:上传的⽂件名* @return*/public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName) {FileInputStream in = null;try{createDir(remotePath);File file = new File(localPath + localFileName);in = new FileInputStream(file);sftp.put(in, remoteFileName);return true;}catch (FileNotFoundException e){e.printStackTrace();}catch (SftpException e){e.printStackTrace();}finally{if (in != null){try{in.close();}catch (IOException e){e.printStackTrace();}}}return false;}/*** 批量上传⽂件* @param remotePath:远程保存⽬录* @param localPath:本地上传⽬录(以路径符号结束)* @param del:上传后是否删除本地⽂件* @return*/public boolean bacthUploadFile(String remotePath, String localPath,boolean del){try{connect();File file = new File(localPath);File[] files = file.listFiles();for (int i = 0; i < files.length; i++)&& files[i].getName().indexOf("bak") == -1){if (this.uploadFile(remotePath, files[i].getName(),localPath, files[i].getName())&& del){deleteFile(localPath + files[i].getName());}}}if (log.isInfoEnabled()){("upload file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is "+ files.length);}return true;}catch (Exception e){e.printStackTrace();}finally{this.disconnect();}return false;}/*** 删除本地⽂件* @param filePath* @return*/public boolean deleteFile(String filePath){File file = new File(filePath);if (!file.exists()){return false;}if (!file.isFile()){return false;}boolean rs = file.delete();if (rs && log.isInfoEnabled()){("delete file success from local.");}return rs;}/*** 创建⽬录* @param createpath* @return*/public boolean createDir(String createpath){try{if (isDirExist(createpath)){this.sftp.cd(createpath);return true;}String pathArry[] = createpath.split("/");StringBuffer filePath = new StringBuffer("/");for (String path : pathArry){if (path.equals(""))}filePath.append(path + "/");if (isDirExist(filePath.toString())){sftp.cd(filePath.toString());}else{// 建⽴⽬录sftp.mkdir(filePath.toString());// 进⼊并设置为当前⽬录sftp.cd(filePath.toString());}}this.sftp.cd(createpath);return true;}catch (SftpException e){e.printStackTrace();}return false;}/*** 判断⽬录是否存在* @param directory* @return*/public boolean isDirExist(String directory){boolean isDirExistFlag = false;try{SftpATTRS sftpATTRS = sftp.lstat(directory);isDirExistFlag = true;return sftpATTRS.isDir();}catch (Exception e){if (e.getMessage().toLowerCase().equals("no such file")) {isDirExistFlag = false;}}return isDirExistFlag;}/*** 删除stfp⽂件* @param directory:要删除⽂件所在⽬录* @param deleteFile:要删除的⽂件* @param sftp*/public void deleteSFTP(String directory, String deleteFile) {try{// sftp.cd(directory);sftp.rm(directory + deleteFile);if (log.isInfoEnabled()){("delete file success from sftp.");}}catch (Exception e){e.printStackTrace();}}/*** 如果⽬录不存在就创建⽬录public void mkdirs(String path){File f = new File(path);String fs = f.getParent();f = new File(fs);if (!f.exists()){f.mkdirs();}}/*** 列出⽬录下的⽂件** @param directory:要列出的⽬录* @param sftp* @return* @throws SftpException*/public Vector listFiles(String directory) throws SftpException {return sftp.ls(directory);}public String getHost(){return host;}public void setHost(String host){this.host = host;}public String getUsername(){return username;}public void setUsername(String username){ername = username;}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 ChannelSftp getSftp(){return sftp;}public void setSftp(ChannelSftp sftp){/**测试*/public static void main(String[] args){SFTPUtils sftp = null;// 本地存放地址String localPath = "D:/tomcat5/webapps/ASSESS/DocumentsDir/DocumentTempDir/txtData/"; // Sftp下载路径String sftpPath = "/home/assess/sftp/jiesuan_2/2014/";List<String> filePathList = new ArrayList<String>();try{sftp = new SFTPUtils("10.163.201.115", "tdcp", "tdcp");sftp.connect();// 下载sftp.batchDownLoadFile(sftpPath, localPath, "ASSESS", ".txt", true);}catch (Exception e){e.printStackTrace();}finally{sftp.disconnect();}}}5.需要的时间辅助类,顺带记下,下次可以直接拿来⽤/*** 时间处理⼯具类(简单的)* @author Aaron* @date 2014-6-17* @time 下午1:39:44* @version 1.0*/public class DateUtil {/*** 默认时间字符串的格式*/public static final String DEFAULT_FORMAT_STR = "yyyyMMddHHmmss";public static final String DATE_FORMAT_STR = "yyyyMMdd";/*** 获取系统时间的昨天* @return*/public static String getSysTime(){Calendar ca = Calendar.getInstance();ca.set(Calendar.DATE, ca.get(Calendar.DATE)-1);Date d = ca.getTime();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String a = sdf.format(d);return a;}/*** 获取当前时间* @param date* @return*/public static String getCurrentDate(String formatStr){if (null == formatStr){formatStr=DEFAULT_FORMAT_STR;}return date2String(new Date(), formatStr);}public static String getTodayChar8(String dateFormat){return DateFormatUtils.format(new Date(), dateFormat);}/*** 将Date⽇期转换为String* @param date* @param formatStr* @return*/public static String date2String(Date date, String formatStr){if (null == date || null == formatStr){return "";}SimpleDateFormat df = new SimpleDateFormat(formatStr);return df.format(date);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

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测试,查看表单的请求数据正⽂,我们发现请求中只有⽂件名称,⽽没有⽂件内容。

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说明下载成功}。

如何通过FTP下载文件

如何通过FTP下载文件

如何通过FTP下载文件一、什么是FTPFTP(File Transfer Protocol)即文件传输协议,是用于在计算机之间传输文件的标准协议。

通过FTP,我们可以方便地将文件从一个计算机上传到另一个计算机,或从服务器下载到本地计算机上。

二、准备工作在开始使用FTP下载文件之前,需要进行以下准备工作:1. 安装FTP客户端软件:常见的FTP软件包括FileZilla、CuteFTP、FlashFXP等。

可以根据个人需要选择合适的FTP客户端软件并安装在计算机上。

2. 获取FTP服务器信息:需要知道要从哪个FTP服务器下载文件,包括FTP服务器的地址(通常是一个IP地址或域名)、端口号、用户名和密码。

这些信息通常由FTP服务器的管理员提供。

三、使用FTP客户端下载文件的步骤1. 启动FTP客户端软件并打开连接窗口。

2. 在连接窗口中填写FTP服务器的地址、端口号、用户名和密码等信息,然后点击连接按钮。

3. 连接成功后,FTP客户端软件会显示远程服务器上的文件列表。

浏览文件列表,找到要下载的文件所在的目录。

4. 双击或右键单击要下载的文件,选择下载或保存选项。

5. 指定文件保存的路径和名称,然后点击确定按钮。

6. FTP客户端软件会开始下载文件,并显示下载进度。

下载完成后,可以在指定的路径中找到下载好的文件。

四、注意事项在通过FTP下载文件时,需要注意以下事项,以确保下载过程的顺利进行:1. 确保FTP服务器的地址、端口号、用户名和密码等信息输入正确,否则无法成功连接到FTP服务器。

2. 在下载大文件时,建议使用稳定的网络环境,并确保本地磁盘空间足够。

3. 如果下载过程中出现连接中断或下载失败等情况,可以尝试重新连接或使用其他FTP客户端软件进行下载。

4. 部分FTP服务器需要进行被动模式(PASV)设置,以允许客户端与服务器之间建立数据连接。

如果下载过程中遇到连接问题,可以尝试切换到被动模式。

五、总结通过FTP下载文件是一种常见且便利的方式,适用于从服务器下载文件到本地计算机的场景。

使用ftp下载文件的流程

使用ftp下载文件的流程

使用FTP下载文件的流程1. 简介FTP(File Transfer Protocol)是一种用于在计算机之间传输文件的标准网络协议。

通过FTP,用户可以在不同的系统之间进行文件上传、下载和删除等操作。

在本文中,我们将讨论如何使用FTP下载文件的流程。

2. 准备工作在使用FTP下载文件之前,我们需要进行一些准备工作。

2.1 确定FTP服务器地址和端口号首先,我们需要确定要从哪个FTP服务器下载文件。

通常,FTP服务器的地址是一个IP地址或域名,而端口号一般是21。

获取到FTP服务器的地址和端口号后,我们可以开始配置FTP客户端。

2.2 配置FTP客户端在使用FTP客户端之前,我们需要下载和安装一个FTP客户端软件。

常见的FTP客户端软件包括FileZilla、WinSCP等。

下载安装完毕后,我们需要进行一些配置。

1.打开FTP客户端软件。

2.在配置界面中,输入FTP服务器的地址和端口号。

3.输入登录凭证,包括用户名和密码。

3. 下载文件的流程下面是使用FTP下载文件的详细步骤:3.1 连接FTP服务器1.打开FTP客户端软件。

2.在主界面中,点击连接按钮或输入命令来连接FTP服务器。

3.2 浏览远程目录1.成功连接到FTP服务器后,你将看到远程目录的列表。

2.导航至所需的目录,使用cd命令或点击相应目录进行导航。

3.3 下载文件1.在远程目录中找到要下载的文件。

2.右键单击文件或选择文件并点击下载按钮。

3.指定将文件下载到本地计算机的位置。

4.点击下载按钮开始下载。

3.4 等待下载完成1.下载过程会花费一些时间,取决于文件的大小和您的网络速度。

2.在下载完成之前,请不要关闭FTP客户端或断开与FTP服务器的连接。

3.5 验证文件完整性1.下载完成后,可以使用文件管理器或计算机终端来验证文件的完整性。

2.比较本地文件的哈希值或文件大小与FTP服务器上的文件是否一致。

4. 注意事项在使用FTP下载文件时,有一些注意事项需要我们注意:•确保FTP服务器的地址和端口号是正确的。

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实现文件上传和下载

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

package com.t;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.io.RandomAccessFile;import mons.logging.Log;import mons.logging.LogFactory;import .PrintCommandListener;import .ftp.FTP;import .ftp.FTPClient;import .ftp.FTPFile;import .ftp.FTPReply;/*** 支持断点续传的FTP实用类** @version 0.1 实现基本断点上传下载* @version 0.2 实现上传下载进度汇报* @version 0.3 实现中文目录创建及中文文件创建,添加对于中文的支持* @author 张连明* @date May 24, 2011 3:29:28 PM*/public class FTPEngine {private static Log log = LogFactory.getLog(FTPEngine.class);// 枚举类UploadStatus代码public enum UploadStatus {Create_Directory_Fail, // 远程服务器相应目录创建失败Create_Directory_Success, // 远程服务器闯将目录成功Upload_New_File_Success, // 上传新文件成功Upload_New_File_Failed, // 上传新文件失败File_Exits, // 文件已经存在Remote_Bigger_Local, // 远程文件大于本地文件Upload_From_Break_Success, // 断点续传成功Upload_From_Break_Failed, // 断点续传失败Delete_Remote_Faild; // 删除远程文件失败}// 枚举类DownloadStatus代码public enum DownloadStatus {Remote_File_Noexist, // 远程文件不存在Local_Bigger_Remote, // 本地文件大于远程文件Download_From_Break_Success, // 断点下载文件成功Download_From_Break_Failed, // 断点下载文件失败Download_New_Success, // 全新下载文件成功Download_New_Failed; // 全新下载文件失败}public FTPClient ftpClient = new FTPClient();private String host;private int port;private String username;private String password;// private String localFilePath;// private String remoteFilePath;public FTPEngine(String host, int port, String username, String password) { // 设置将过程中使用到的命令输出到控制台this.host = host;this.port = port;ername = username;this.password = password;this.ftpClient.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(System.out)));}/** *//*** 连接到FTP服务器** @param hostname* 主机名* @param port* 端口* @param username* 用户名* @param password* 密码* @return 是否连接成功* @throws IOException*/public boolean connect() throws IOException {ftpClient.connect(host, port);ftpClient.setControlEncoding("GBK");if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { if (ftpClient.login(username, password)) {return true;}}disconnect();return false;}/** *//*** 从FTP服务器上下载文件,支持断点续传,上传百分比汇报** @param remote* 远程文件路径* @param local* 本地文件路径* @return 上传的状态* @throws IOException*/public DownloadStatus download(String remote, String local) throws IOException {// 设置被动模式ftpClient.enterLocalPassiveMode();// 设置以二进制方式传输ftpClient.setFileType(FTP.BINARY_FILE_TYPE);DownloadStatus result;// 检查远程文件是否存在FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("UTF-8"), "iso-8859-1"));if (files.length != 1) {log.error("远程文件不存在");return DownloadStatus.Remote_File_Noexist;}long lRemoteSize = files[0].getSize();File f = new File(local);// 本地存在文件,进行断点下载if (f.exists()) {long localSize = f.length();// 判断本地文件大小是否大于远程文件大小if (localSize >= lRemoteSize) {log.error("本地文件大于远程文件,下载中止");return DownloadStatus.Local_Bigger_Remote;}// 进行断点续传,并记录状态FileOutputStream out = new FileOutputStream(f, true);ftpClient.setRestartOffset(localSize);InputStream in = ftpClient.retrieveFileStream(new String(remote .getBytes("UTF-8"), "iso-8859-1"));byte[] bytes = new byte[1024];long step = lRemoteSize / 100;long process = localSize / step;int c;while ((c = in.read(bytes)) != -1) {out.write(bytes, 0, c);localSize += c;long nowProcess = localSize / step;if (nowProcess > process) {process = nowProcess;if (process % 10 == 0)("下载进度:" + process + "%");// TODO 更新文件下载进度,值存放在process变量中}}in.close();out.close();boolean isDo = pletePendingCommand();if (isDo) {result = DownloadStatus.Download_From_Break_Success;} else {result = DownloadStatus.Download_From_Break_Failed;}} else {OutputStream out = new FileOutputStream(f);InputStream in = ftpClient.retrieveFileStream(new String(remote .getBytes("UTF-8"), "iso-8859-1"));byte[] bytes = new byte[1024];long step = lRemoteSize / 100;long process = 0;long localSize = 0L;int c;while ((c = in.read(bytes)) != -1) {out.write(bytes, 0, c);localSize += c;long nowProcess = localSize / step;if (nowProcess > process) {process = nowProcess;if (process % 10 == 0)("下载进度:" + process + "%");// TODO 更新文件下载进度,值存放在process变量中}}in.close();out.close();boolean upNewStatus = pletePendingCommand();if (upNewStatus) {result = DownloadStatus.Download_New_Success;} else {result = DownloadStatus.Download_New_Failed;}}return result;}/** *//*** 上传文件到FTP服务器,支持断点续传** @param local* 本地文件名称,绝对路径* @param remote* 远程文件路径,使用/home/directory1/subdirectory/file.ext或是* http://IP:PORT/subdirectory/file.ext* 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构* @return 上传结果* @throws IOException*/public UploadStatus upload(String local, String remote) throws IOException {// 设置PassiveMode传输ftpClient.enterLocalPassiveMode();// 设置以二进制流的方式传输ftpClient.setFileType(FTP.BINARY_FILE_TYPE);ftpClient.setControlEncoding("UTF-8");UploadStatus result;// 对远程目录的处理String remoteFileName = remote;if (remote.contains("/")) {remoteFileName = remote.substring(stIndexOf("/") + 1);// 创建服务器远程目录结构,创建失败直接返回if (CreateDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) { return UploadStatus.Create_Directory_Fail;}}// 检查远程是否存在文件FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"));if (files.length == 1) {long remoteSize = files[0].getSize();File f = new File(local);long localSize = f.length();if (remoteSize == localSize) {return UploadStatus.File_Exits;} else if (remoteSize > localSize) {return UploadStatus.Remote_Bigger_Local;}// 尝试移动文件内读取指针,实现断点续传result = uploadFile(remoteFileName, f, ftpClient, remoteSize);// 如果断点续传没有成功,则删除服务器上文件,重新上传if (result == UploadStatus.Upload_From_Break_Failed) {if (!ftpClient.deleteFile(remoteFileName)) {return UploadStatus.Delete_Remote_Faild;}result = uploadFile(remoteFileName, f, ftpClient, 0);}} else {result = uploadFile(remoteFileName, new File(local), ftpClient, 0);}return result;}/*** 删除FTP服务器的文件** @param remotePath* @param remoteFile* @return*/public boolean delete(String remotePath, String remoteFile) {boolean status = false;try {boolean flag = ftpClient.deleteFile(remotePath + remoteFile);if (flag)if (ftpClient.getReplyCode() == 250)status = true;} catch (IOException e) {log.error("删除文件" + remotePath + remoteFile + " 失败!!!");e.printStackTrace();}return status;}/** *//*** 断开与远程服务器的连接** @throws IOException*/public void disconnect() throws IOException {if (ftpClient.isConnected()) {ftpClient.disconnect();}}/** *//*** 递归创建远程服务器目录** @param remote* 远程服务器文件绝对路径* @param ftpClient* FTPClient 对象* @return 目录创建是否成功* @throws IOException*/public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient) throws IOException {UploadStatus status = UploadStatus.Create_Directory_Success;String directory = remote.substring(0, stIndexOf("/") + 1);if (!directory.equalsIgnoreCase("/")&& !ftpClient.changeWorkingDirectory(new String(directory.getBytes("UTF-8"), "iso-8859-1"))) {// 如果远程目录不存在,则递归创建远程服务器目录int start = 0;int end = 0;if (directory.startsWith("/")) {start = 1;} else {start = 0;}end = directory.indexOf("/", start);while (true) {String subDirectory = new String(remote.substring(start, end).getBytes("UTF-8"), "iso-8859-1");if (!ftpClient.changeWorkingDirectory(subDirectory)) {if (ftpClient.makeDirectory(subDirectory)) {ftpClient.changeWorkingDirectory(subDirectory);} else {log.error("创建目录失败");return UploadStatus.Create_Directory_Fail;}}start = end + 1;end = directory.indexOf("/", start);// 检查所有目录是否创建完毕if (end <= start) {break;}}}return status;}/** *//*** 上传文件到服务器,新上传和断点续传** @param remoteFile* 远程文件名,在上传之前已经将服务器工作目录做了改变* @param localFile* 本地文件File句柄,绝对路径* @param processStep* 需要显示的处理进度步进值* @param ftpClient* FTPClient 引用* @return* @throws IOException*/public UploadStatus uploadFile(String remoteFile, File localFile,FTPClient ftpClient, long remoteSize) throws IOException { UploadStatus status;// 显示进度的上传long step = localFile.length();double process = 0;long localreadbytes = 0L;RandomAccessFile raf = new RandomAccessFile(localFile, "r");OutputStream out = ftpClient.appendFileStream(new String(remoteFile .getBytes("UTF-8"), "UTF-8"));// 断点续传if (remoteSize > 0) {ftpClient.setRestartOffset(remoteSize);process = remoteSize / step;raf.seek(remoteSize);localreadbytes = remoteSize;}byte[] bytes = new byte[1024];int c;while ((c = raf.read(bytes)) != -1) {out.write(bytes, 0, c);localreadbytes += c;if (localreadbytes / step != process) {process = localreadbytes / step;("上传进度:" + process * 100 + "%");// TODO 汇报上传状态}}out.flush();raf.close();out.close();boolean result = pletePendingCommand();if (remoteSize > 0) {status = result ? UploadStatus.Upload_From_Break_Success: UploadStatus.Upload_From_Break_Failed;} else {status = result ? UploadStatus.Upload_New_File_Success: UploadStatus.Upload_New_File_Failed;}return status;}/*** 判断指定文件名的文件是否存在<br>* 返回匹配到的文件个数** @param fileName* @return*/public int doExistsFile(String fileName) {try {FTPFile[] file = ftpClient.listFiles(fileName);return file.length;} catch (IOException e) {e.printStackTrace();return 0;}}public static void main(String[] args) throws IOException {System.out.println(new FTPEngine("192.168.22.100", 21, "tendon", "tendon").connect());}}除此之外需要导入common- logging.jar和commons-net-3.0.jar包文件。

相关文档
最新文档