Java implementation ftp file upload and file download _java

Source: Internet
Author: User
Tags file upload ftp file ftp login ftp client ftp protocol

This example for you to share the two Java ftp file upload to download the way for you to refer to, the specific content as follows

The first way:

Package com.cloudpower.util;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;

Import java.io.IOException;
Import Sun.net.TelnetInputStream;
Import Sun.net.TelnetOutputStream;

Import sun.net.ftp.FtpClient; /** * Java-brought API for FTP operation * @Title: Ftp.java * @author: Zhou Lingbin/public class FTP {/** * local file name */Private String Lo
 Calfilename;
 /** * Remote File name */private String remotefilename;

 /** * FTP client * * Private ftpclient ftpclient;
  /** * Server connection * @param IP Server IP * @param port server ports * @param user name * @param password Password * @param path server * @author Zhou Lingbin * @date 2012-7-11/public void ConnectServer (string ip, int port, string user, string password, S Tring path) {try {* * * The two methods of connecting the server *******///First method///ftpclient = new ftpclient ();//Ftpclient.openserve
   R (IP, port);
   
   The second method ftpclient = new FtpClient (IP);
   Ftpclient.login (user, password);
   Set into a 2-ftpclient.binary transmission (); System.ouT.PRINTLN ("Login success!");
   if (path.length ()!= 0) {//switch directories on the remote system to the directory FTPCLIENT.CD (path) specified in parameter path;
  } ftpclient.binary ();
   catch (IOException ex) {ex.printstacktrace ();
  throw new RuntimeException (ex); }/** * Close connection * @author Zhou Lingbin * @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); /** * Upload file * @param localfile Local file * @param remotefile remote file * @author Zhou Lingbin * @date 2012-7-11/Public V
  OID Upload (string localfile, String remotefile) {this.localfilename = LocalFile;
  This.remotefilename = RemoteFile;
  Telnetoutputstream OS = null;
  FileInputStream is = null;
   try {//Add the remote file to the output stream OS = Ftpclient.put (this.remotefilename);
   Gets the input stream of the local file file_in = new file (this.localfilename); is = new FileInputStream (fiLE_IN);
   Create a buffer 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 (); /** * Download file * @param remotefile Remote file path (server side) * @param localfile Local file path (client) * @author Zhou Lingbin * @dat
  E 2012-7-11 */public void Download (string remotefile, String localfile) {Telnetinputstream is = null;
  FileOutputStream OS = null;
   try {//Get file filename on the remote machine, and use Telnetinputstream to transfer the file to local.
   is = Ftpclient.get (remotefile);
   File file_in = new file (LocalFile);
   OS = new FileOutputStream (file_in); Byte[]bytes = new byte[1024];
   int C;
   while ((c = is.read (bytes))!=-1) {os.write (bytes, 0, c);
  } System.out.println ("Download Success");
   catch (IOException ex) {System.out.println ("not download");
   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 ();
  }}} public static void Main (string agrs[]) {string filepath[] = {"/temp/aa.txt", "/temp/regist.log"};

  String localfilepath[] = {"C:\\tmp\\1.txt", "C:\\tmp\\2.log"};
  FTP fu = new ftp ();
  
  * * Use the default port number, username, password, and the root directory to connect to the FTP server * * Fu.connectserver ("127.0.0.1", "Anonymous", "ieuser@", "/temp");
  download for (int i = 0; i < filepath.length i++) {fu.download (Filepath[i], localfilepath[i]);
  String LocalFile = "e:\\ number. txt"; STring remotefile = "/temp/haha txt";
  Upload Fu.upload (LocalFile, remotefile);
 Fu.closeconnect ();
 }
}


This way there is nothing to say, relatively simple, there is no problem of Chinese garbled. There seems to be a flaw, can not operate large files, interested friends can try.

The second way:

public class Ftpapche {private static ftpclient ftpclient = new FtpClient ();
 private static String encoding = System.getproperty ("file.encoding");
  /** * Description: Uploading files to FTP server * * @Version1.0 * @param URL * FTP server hostname * @param port * FTP server ports  * @param username * FTP login account * @param password * FTP login password * @param path * FTP server to save the directory, if the root directory is "/" * @param FileName * uploaded to FTP server file name * @param input * Local file Import stream * @return successfully returns TRUE, otherwise returns false/* public static Boolean U
  Ploadfile (string url, int port, string username, string password, string path, string filename, InputStream input) {

  Boolean result = false;
   try {int reply;
   If the default port is used, the FTP server Ftpclient.connect (URL) can be directly connected using the Ftp.connect (URL) method;
   Ftp.connect (URL, port);//Connect FTP server/login ftpclient.login (username, password);
   ftpclient.setcontrolencoding (encoding);
   Verify Connection Success reply = Ftpclient.getreplycode (); if (!
    Ftpreply.ispositivecompletion (Reply)) {System.out.println ("Connection failed");
    Ftpclient.disconnect ();
   return result;
   //Transfer working directory to the specified directory boolean change = ftpclient.changeworkingdirectory (path);
   Ftpclient.setfiletype (Ftp.binary_file_type);
    if (change) {result = Ftpclient.storefile (new String (Filename.getbytes (encoding), "iso-8859-1"), input);
    if (result) {System.out.println ("Upload success!");
   } input.close ();
  Ftpclient.logout ();
  catch (IOException e) {e.printstacktrace ();
    finally {if (ftpclient.isconnected ()) {try {ftpclient.disconnect ();
 The catch (IOException IoE) {}} return result; /** * Upload the local file to the FTP server */public void Testuploadfromdisk () {try {fileinputstream in = new Fileinputstr
   EAM (New File ("e:/number. txt");
   Boolean flag = UploadFile ("127.0.0.1", "ZLB", "123", "/", "haha. txt", in);
  SYSTEM.OUT.PRINTLN (flag);
  catch (FileNotFoundException e) {e.printstacktrace (); }/** * Description: Downloading files from FTP server * *@Version1.0 * @param URL * FTP server hostname * @param port * FTP server PORTS * @param username * FTP Login account * @para
  M Password * FTP login password * @param remotepath * The relative path on the FTP server * @param filename * The filename to download * @param localpath * Save to Local path after download * @return/public static Boolean downfile (string url, int port, string username, string passwor
  D, String RemotePath, String fileName, String localpath) {Boolean result = false;
   try {int reply;
   
   ftpclient.setcontrolencoding (encoding);
    * * to upload and download Chinese files, there are suggestions to use the following two sentences instead of the * New String (remotepath.getbytes (encoding), "Iso-8859-1") transcoding.
    * After testing, pass.
*///Ftpclientconfig conf = new Ftpclientconfig (FTPCLIENTCONFIG.SYST_NT);

   Conf.setserverlanguagecode ("en");
   Ftpclient.connect (URL, port); If you use the default port, you can use the Ftp.connect (URL) method to connect directly to the FTP server Ftpclient.login (username, password);//Login//settings file Transfer type is binary ftpclient
   . Setfiletype (Ftpclient.binary_file_type); Get the FTP login answer code reply = FtpclienT.getreplycode (); Verify that the login is successful if (!
    Ftpreply.ispositivecompletion (Reply)) {ftpclient.disconnect ();
    SYSTEM.ERR.PRINTLN ("FTP server refused connection.");
   return result;
   //Transfer to the FTP server directory to the specified directory Ftpclient.changeworkingdirectory (new String (Remotepath.getbytes (encoding), "iso-8859-1"));
   Get file list ftpfile[] fs = Ftpclient.listfiles (); for (Ftpfile ff:fs) {if (Ff.getname (). Equals (FileName)) {file LocalFile = new File (LocalPath + "/" + Ff.getna
     Me ());
     OutputStream is = new FileOutputStream (localfile);
     Ftpclient.retrievefile (Ff.getname (), is);
    Is.close ();
   } ftpclient.logout ();
  result = true;
  catch (IOException e) {e.printstacktrace ();
    finally {if (ftpclient.isconnected ()) {try {ftpclient.disconnect ();
 The catch (IOException IoE) {}} return result; /** * Download files on FTP server to local */public void Testdownfile () {try {Boolean flag = Downfile ("127.0.0.1", "Z"
 LB ",    "123", "/", "haha. txt", "d:/");
  SYSTEM.OUT.PRINTLN (flag);
  catch (Exception e) {e.printstacktrace ();
  } public static void Main (string[] args) {Ftpapche fa = new Ftpapche ();
 Fa.testdownfile ();
 }
}


This way words need to pay attention to Chinese garbled problem, if you set inappropriate, there may be uploaded file name will be garbled, and sometimes simply upload not up, of course, will not be prompted with you, because there is no exception. On the internet to find a lot of solutions, opinions, almost all from a copy of the past, also did not pass their own really test. To this end, but also suffered a lot. Roughly divided into the following two kinds of solutions:
1, add the following three sentences can be solved

Ftpclient.setcontrolencoding ("GBK");

Ftpclientconfig conf = new Ftpclientconfig (FTPCLIENTCONFIG.SYST_NT);
Conf.setserverlanguagecode ("en");
Answer: after testing, fundamentally unworkable, the problem remains

2, similar to the above method, but I think this way more reliable

First, add ftpclient.setcontrolencoding ("GBK"), this sentence, and then, all the Chinese to the code "ISO-8859-1" format, as follows:

Ftpclient.changeworkingdirectory (New String (Remotepath.getbytes ("GBK"), "iso-8859-1");

Answer: after testing, still not workable, the reason I said this way more reliable, please continue to look down

First, let's talk about the reason for transcoding:

Because in the FTP protocol, the specified filename is encoded as iso-8859-1, so the directory name or filename needs to be transcoding.

The next question is, what encoding should we convert to this format. Therefore, there is a second solution-converting the GBK format to the iso-8859-1 format. And, some people say, it has to be this way. In fact, the reason why they can say so, I think it is entirely a coincidence. The real principle is that, since the FTP protocol is the code format "Iso-8859-1", then we do have to convert the format, and then the server when the file is automatically converted to the system with the encoding format, so the key is not to specify why format, but depends on the FTP server encoding format. Therefore, if the FTP system's encoding format is "GBK", the second method will certainly succeed, but if the system's encoding format is "UTF-8", it will still appear garbled. So, we can only get the coding format of the system through code, and then convert it to iso-8859-1 encoding format through this encoding format. Get the following way:

private static String encoding = System.getproperty ("file.encoding");

The above code through their own testing, hope to solve the problem for everyone!

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.