Java implementation of FTP file upload download involves Chinese path and Chinese file __java

Source: Internet
Author: User
Tags ftp connection ftp file ftp upload file log4j
Reference three jar packages  Commons-net-1.4.1.jar   Jakarta-oro-2.0.8.jar  Log4j-1.2.17.jar
FTP instance
<pre name= "code" class= "Java" >package com.ftp;

/**
 * FTP LINK constant * * */Public
class Ftp {

	private String IPADDR;//IP address
	
	private Integer port;//port number C10/>private string username;//user name
	
	private string pwd;//password
	
	private string path;//aaa path public

	string Getipaddr () {return
		ipaddr;
	}

	public void Setipaddr (String ipaddr) {
		this.ipaddr = ipaddr;
	}

	Public Integer Getport () {return
		port;
	}

	public void Setport (Integer port) {
		this.port = port;
	}

	Public String GetUserName () {return
		userName;
	}

	public void Setusername (String userName) {
		this.username = userName;
	}

	Public String getpwd () {return
		pwd;
	}

	public void SetPwd (String pwd) {
		this.pwd = pwd;
	}

	Public String GetPath () {return
		path;
	}

	public void SetPath (String path) {
		This.path = path;
	}
	
	
}


<pre name= "code" class= "Java" >package com.ftp;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;




Import Java.io.OutputStream;
Import org.apache.commons.net.ftp.FTPClient;
Import Org.apache.commons.net.ftp.FTPClientConfig;
Import Org.apache.commons.net.ftp.FTPFile;
Import org.apache.commons.net.ftp.FTPReply;

Import Org.apache.log4j.Logger;
	
	public class Ftputil {private static Logger Logger=logger.getlogger (Ftputil.class);
	
	private static ftpclient ftp; /** * Get FTP Connection * @param f * @return * @throws Exception/public static Boolean Connectftp (FTP f) throws Except
		ion{ftp=new ftpclient ();
		Boolean flag=false;
		int reply;
		if (F.getport () ==null) {Ftp.connect (F.getipaddr (), 21);
		}else{Ftp.connect (F.getipaddr (), F.getport ());
		} ftp.login (F.getusername (), f.getpwd ());
		Ftp.setfiletype (Ftpclient.binary_file_type);      
	    Reply = Ftp.getreplycode (); if (! Ftpreply.ispositivecomPletion (Reply)) {ftp.disconnect ();      
	    return flag;      
	    } ftp.changeworkingdirectory (F.getpath ());      
	    Flag = true;
	return flag; /** * Close FTP connection */public static void Closeftp () {if (Ftp!=null && ftp.isconnected ()) {try {FTP
				. Logout ();
			Ftp.disconnect ();
			catch (IOException e) {e.printstacktrace ();
		/** * FTP upload file * @param f * @throws Exception/public static void upload (file f) throws exception{
			if (F.isdirectory ()) {ftp.makedirectory (F.getname ());
			Ftp.changeworkingdirectory (F.getname ());
			String[] Files=f.list ();
				for (String fstr:files) {file File1=new file (F.getpath () + "/" +fstr);
					if (File1.isdirectory ()) {upload (file1);
				Ftp.changetoparentdirectory ();
					}else{file File2=new file (F.getpath () + "/" +fstr);
					FileInputStream input=new FileInputStream (file2);
					Ftp.storefile (File2.getname (), input); Input.close ();
			}}else{file File2=new file (F.getpath ());
			FileInputStream input=new FileInputStream (file2);
			Ftp.storefile (File2.getname (), input);
		Input.close ();
	}/** * Download Connection configuration * @param f * @param localbasedir Local directory * @param remotebasedir remote directory * @throws Exception * * public static void Startdown (FTP f,string localbasedir,string remotebasedir) throws exception{if (Ftputil.connectftp ( 
	            f)) {try {ftpfile[] files = null; 
	            Boolean changedir = Ftp.changeworkingdirectory (Remotebasedir); if (Changedir) {ftp.setcontrolencoding ("iso-8859-1");/note encoding format ftpclientconfig conf = new FTP
	            	ClientConfig (Ftpclientconfig.syst_unix); 
	                Conf.setserverlanguagecode ("en");//Chinese files = ftp.listfiles (); for (int i = 0; i < files.length. i++) {try{do Wnloadfile (Files[i], LocalbasediR, Remotebasedir); 
	                    	}catch (Exception e) {logger.error (e); 
	                    Logger.error ("<" +files[i].getname () + "Download Failed"); 
	        	catch (Exception e) {logger.error (e); 
	        Logger.error ("Exception occurred during download");
		}}else{Logger.error ("Connection failed!"); /** * * Download FTP file * When you need to download the ftp file, call this method * based on-get the file name, local address, remote address-download * @param ft PFile * @param relativelocalpath * @param relativeremotepath * @throws Exception * * Private STA 
    	
        
    	
        tic void DownloadFile (Ftpfile ftpfile, String relativelocalpath,string relativeremotepath) throws Exception { if (Ftpfile.isfile ()) {string Filename=new string (Ftpfile.getname (). GetBytes ("Iso-8859-1"
			
            ), "Utf-8");/related to the Chinese document SYSTEM.OUT.PRINTLN (filename); 
            if (Ftpfile.getname (). IndexOf ("?") = = 1) {    OutputStream outputstream = null; 
                    try {file locafile= new file (relativelocalpath+ filename); If the file already exists, return if (Locafile.exists ()) {SYSTEM.OUT.PRINTLN (hint: The destination file already exists ....
                        "); 
                    Return
                        
                        }else{outputstream = new FileOutputStream (relativelocalpath+ filename); 
                        Ftp.retrievefile (Ftpfile.getname (), outputstream); 
                        Outputstream.flush (); 
                    Outputstream.close ();
                The catch (Exception e) {logger.error (e); Finally {try {if (OutputStream!= null) {OU 
                        Tputstream.close (); 
The catch (IOException e) {logger.error ("Output file stream exception");                    }} else {String Newlocalrelatepath = relativ 
            Elocalpath + ftpfile.getname (); 
            String newremote = new String (relativeremotepath+ ftpfile.getname (). toString ()); 
            File FL = new file (Newlocalrelatepath); 
            if (!fl.exists ()) {fl.mkdirs (); 
                try {newlocalrelatepath = Newlocalrelatepath + '/'; 
                Newremote = Newremote + "/"; 
                String Currentworkdir = Ftpfile.getname (). toString (); 
                Boolean changedir = Ftp.changeworkingdirectory (Currentworkdir); 
                    if (Changedir) {ftpfile[] files = null; 
                    Files = Ftp.listfiles (); for (int i = 0; i < files.length i++) {downloadFile (files[i), Newlocalrelatepath, Newremote) 
                    ; } if (changedIR) {ftp.changetoparentdirectory ();
            The catch (Exception e) {logger.error (e);
			}} public static void Main (string[] args) throws exception{ftp f=new FTP ();
			IP address f.setipaddr ("36.110.85.10");
			FTP User name F.setusername ("P_center");
			FTP Password f.setpwd ("ea65db2fa7f45672");
			Port number F.setport (21);
			Ftputil.connectftp (f);  
			File File = new file ("F:/test/com/test/testng.java");
			Ftputil.upload (file);//String local = "f:/";
			String remote = "/Dalian China News/Postal currency card";   String remoteurl = new String (Remote.getbytes ("Utf-8"), "iso-8859-1")//refers to the Chinese issue according to the actual system code change Ftputil.startdown (f, local,
			Remoteurl);
	   System.out.println ("OK"); }  
	
	
	
}


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.