JAVA implementation of FTP client upload, download, delete __java

Source: Internet
Author: User
Tags create directory ftp connection ftp login ftp server path ftp client ftp protocol server port

Project Download Address: http://download.csdn.net/download/ljj2312/10187480

Engineering structure: (used in the project, supporting the Chinese file name, pro-Test ok!)


Need to download the three jar packages above

FTP Tools class:

Package cn.ftp.util;
Import Java.io.BufferedOutputStream;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;

Import java.net.SocketException;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;

Import org.apache.commons.net.ftp.FTPReply; /** * FTP Tool class * @author LIJJ/public class Ftputil {private final static Log logger = Logfactory.getlog (ftputil.cl
	ASS);

	/** Local character encoding */private static String Local_charset = "GBK";
	
	In the FTP protocol, the specified filename is encoded as iso-8859-1 private static String Server_charset = "Iso-8859-1";
	 /** * Get FtpClient Object * * * @param ftphost * FTP Host Server * * @param ftppassword * FTP login password          * * @param ftpusername *  FTP Login Username * * @param ftpport * FTP port defaults to * * @return/public static ftpclient getftpclient (
		string ftphost, int ftpport, string ftpusername, String ftppassword) {ftpclient ftpclient = null;
			try {ftpclient = new ftpclient (); Ftpclient.connect (Ftphost, FtpPort);//Connect FTP server Ftpclient.login (FtpUserName, FTPPassword);//Login FTP server if (! Ftpreply.ispositivecompletion (Ftpclient.getreplycode ())) {Logger.info ("Not connected to FTP, user name or password error.")
				");
			Ftpclient.disconnect (); else {logger.info ("FTP connection succeeded.")
			");
			} catch (SocketException e) {e.printstacktrace (); Logger.info ("FTP IP address may be wrong, please configure correctly.")
		");
			catch (IOException e) {e.printstacktrace (); Logger.info ("FTP port error, please configure correctly.")
		");
	return ftpclient; /** * Download files from FTP server * * @param ftphost FTP IP Address * * @param ftpusername FTP user name * * @param ftppassword F TP Username Password * * @param ftpport FTP Port * * @param ftppath FTP Server file path format: FTPTEST/AA * * * @param localpath Download to thisLocation Format: h:/download * * @param filename File name */public static void Downloadftpfile (String ftphost, String Ftpusern Ame, string ftppassword, int ftpport, string ftppath, String localpath, String fileName) {FtpClient ftpclient = nul

		L
			try {ftpclient = getftpclient (Ftphost, FtpPort, FtpUserName, FTPPassword); Sets the type of upload file to be binary type if (Ftpreply.ispositivecompletion (Ftpclient.sendcommand ("OPTS UTF8", "on")) {//Turn on server support for UTF-8.
				If server support is encoded with UTF-8, the local encoding (GBK) is used.
			Local_charset = "UTF-8";
			} ftpclient.setcontrolencoding (Local_charset); Ftpclient.enterlocalpassivemode ()//Set Passive mode Ftpclient.setfiletype FTP. Binary_file_type)//Set the transmission mode//upload file//To the Chinese file name for transcoding, otherwise the Chinese name of the file download failed String filenametemp = new String (filename.getbyte
			S (local_charset), server_charset);
			
			Ftpclient.changeworkingdirectory (Ftppath);

			InputStream Retrievefilestream = Ftpclient.retrievefilestream (filenametemp); The first way to download files (recommended)/* File LocalFile = new file (LocalPath + file.sEparatorchar + fileName);
			  OutputStream OS = new FileOutputStream (localfile); Ftpclient.retrievefile (fileName, OS); Os.close ();//The second way to download: the input stream into bytes, and then generate files, this way to facilitate the return of the byte array directly to the foreground JSP page byte[] input2byte = Input2byte (retrievefilestr
			EAM);
			
			Byte2file (Input2byte, LocalPath, fileName);
			if (null!= retrievefilestream) {retrievefilestream.close ();
			The catch (FileNotFoundException e) {logger.error ("not found" + Ftppath + "file");
		E.printstacktrace ();
			catch (SocketException e) {logger.error ("Connection FTP failed.");
		E.printstacktrace ();
			catch (IOException e) {e.printstacktrace (); Logger.error ("file read error.")
			");
		E.printstacktrace ();
					finally {if (ftpclient.isconnected ()) {try {//Exit login ftpclient.logout (); 
				Close connection Ftpclient.disconnect (); catch (IOException e) {}}}}/** * Description: Uploading files to FTP server * * @param host * FTP server H Ostname * @param port * FTP server ports * @param userName * FTP login account * @param password * FTP login password * @param basepath * FTP Server base directory * PARAM filePath * FTP server file storage path. For example, date of deposit:/2015/01/01. The file path is Basepath+filepath * @param filename * uploaded to the FTP server file name * @param input stream * @return Returns true successfully, otherwise returns false */public static Boolean UploadFile (string ftphost, int ftpport, string ftpusername, String FTPPASSW
		Ord, String basepath, String filePath, string filename, InputStream input) {Boolean result = false;
		FtpClient ftpclient = null;
			try {int reply;
			FtpClient = Getftpclient (Ftphost, FtpPort, FtpUserName, FTPPassword);
			Reply = Ftpclient.getreplycode (); if (!
				Ftpreply.ispositivecompletion (Reply)) {ftpclient.disconnect ();
			return result; //Switch to upload directory if (!ftpclient.changeworkingdirectory (BasePath + filePath)) {//If directory does not exist create directory string[] dirs = fi
				Lepath.split ("/");
				String TempPath = BasePath;
		for (String dir:dirs) {			if (null = Dir | |
					". Equals (dir)) continue;
					TempPath + = "/" + dir;
						if (!ftpclient.changeworkingdirectory (TempPath)) {if (!ftpclient.makedirectory (TempPath)) {return result;
						else {ftpclient.changeworkingdirectory (TempPath); The type of upload file is binary type if (Ftpreply.ispositivecompletion (Ftpclient.sendcommand ("OPTS UTF8", "on"))
				{//Turn on server support for UTF-8, if server support is encoded with UTF-8, use local encoding (GBK).
			Local_charset = "UTF-8";
			} ftpclient.setcontrolencoding (Local_charset); Ftpclient.enterlocalpassivemode ()//Set Passive mode Ftpclient.setfiletype FTP.
			Binary_file_type)//Set the transmission mode//upload file filename = new String (Filename.getbytes (Local_charset), server_charset);
			if (!ftpclient.storefile (filename, input)) {return result;
			} if (null!= input) {input.close ();
		result = true;
		catch (IOException e) {e.printstacktrace (); finally {if (ftpclient.isconnected ()) {try {//exit login FTpclient.logout ();
				Close connection Ftpclient.disconnect ();
	The catch (IOException IoE) {}} return result; /** * Delete File not tested * * @param hostname * FTP server address * @param port * FTP Server port number * @param
	 Username * FTP Login account * @param password * FTP login password * @param pathname * FTP Server Save directory  * @param filename * Name of the file to be deleted * @return/public static Boolean DeleteFile (String ftphost, int ftpport,
		String FtpUserName, String FTPPassword, String pathname, String filename) {Boolean flag = false;
		FtpClient ftpclient = new FtpClient ();
			try {ftpclient = getftpclient (Ftphost, FtpPort, FtpUserName, FTPPassword);
			Verify that the FTP server is logged on successfully int replycode = Ftpclient.getreplycode (); if (!
			Ftpreply.ispositivecompletion (Replycode)) {return flag;
			}//Toggle FTP directory Ftpclient.changeworkingdirectory (pathname); Sets the type of upload file to be binary type if (Ftpreply.ispositivecompletion (Ftpclient.sendcommand) ("OPTS UTF8 "," on ")) {//Turn on server support for UTF-8, use local encoding (GBK) if server support is encoded with UTF-8.
			Local_charset = "UTF-8";
			} ftpclient.setcontrolencoding (Local_charset); Ftpclient.enterlocalpassivemode ()//Set Passive mode Ftpclient.setfiletype FTP.
			Binary_file_type)//Set the transmission mode//to the Chinese name for transcoding filename = new String (Filename.getbytes (Local_charset), server_charset);
			Ftpclient.dele (filename);
		Flag = true;
		catch (Exception e) {e.printstacktrace ();
					finally {if (ftpclient.isconnected ()) {try {//Exit login ftpclient.logout ();
				Close connection Ftpclient.disconnect ();
	The catch (IOException e) {}}} return flag;
	///Convert byte array to input stream public static final InputStream byte2input (byte[] buf) {return new Bytearrayinputstream (BUF); }///Convert input to byte[] public static final byte[] Input2byte (InputStream instream) throws IOException {Bytearrayoutputstr
		EAM swapstream = new Bytearrayoutputstream ();
		byte[] buff = new byte[100];
		int rc = 0; while (rc = Instream.reaD (Buff, 0, m)) > 0) {swapstream.write (buff, 0, RC);
		} byte[] in2b = Swapstream.tobytearray ();
	return in2b; Convert byte[to file public static void Byte2file (byte[] buf, String filePath, String fileName) {Bufferedoutputstream bo
		s = null;
		FileOutputStream fos = null;
		File file = null;
			try {file Dir = new File (FilePath);
			if (!dir.exists () && dir.isdirectory ()) {dir.mkdirs ());
			File = new File (FilePath + file.separator + fileName);
			FOS = new FileOutputStream (file);
			BOS = new Bufferedoutputstream (FOS);
		Bos.write (BUF);
		catch (Exception e) {e.printstacktrace ();
				Finally {if (Bos!= null) {try {bos.close ();
				catch (IOException e) {e.printstacktrace ();
				} if (fos!= null) {try {fos.close ();
				catch (IOException e) {e.printstacktrace (); }
			}
		}
	}
}



Test class:

Import Java.io.File;
Import Java.io.FileInputStream;

Import java.io.FileNotFoundException;

  
Import Cn.ftp.util.FtpUtil;
        public class Ftpmain {public static void main (string[] args) throws FileNotFoundException {//ftp server IP address  
        String ftphost = "10.18.17.190";  
        FTP server port int ftpport = 21;
        FTP Server user name String ftpusername = "AA";  
        FTP server password String ftppassword = "57GHV2MH"; 
       FTP server path String ftppath = "ftpdir/";  
        Local path String localpath = "e://";  
        
        
        filename String filename = "2.docx"; Download//download files from FTP root directory to e disk//Ftputil.downloadftpfile (Ftphost, FtpUserName, FTPPassword, FtpPort, Ftppath, loc  
       
        Alpath, FileName); 
        Upload//upload e-disk files to the FTP root directory/*fileinputstream in=new fileinputstream (New file ("e:/" + fileName); Ftputil.uploadfile (Ftphost, FtpPort, FtpUserName, FTPPassword, "ftpdir/", "/", fileName, in);*//delete//delete files under FTP root directory Ftputil.deletefile (ftphost, FtpPort, FtpUserName, FTPPassword, "ft
        
        
	pdir/"," 2.docx ");   }
}

Project Download Address: http://download.csdn.net/download/ljj2312/10187480

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.