Java using Apache upload files to ftp Commons-net-3.2.jar

Source: Internet
Author: User
Tags ftp new set response code

Import Java.io.ByteArrayInputStream;
Import Java.io.DataInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.io.UnsupportedEncodingException;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;

Import java.util.List;
Import Sun.net.TelnetInputStream;

Import Sun.net.TelnetOutputStream;
Import Org.apache.commons.net.ftp.FTP;
Import org.apache.commons.net.ftp.FTPClient;


Import Org.apache.commons.net.io.SocketInputStream;
     public class Ftputil {private FtpClient ftpclient;
     /** * Transfer mode is a binary file.
    * * public static final int binary_file_type = Ftp.binary_file_type;  /** * connectserver * Connect FTP Server * @throws java.io.IOException * @param path folder, NULL represents root * @param password Password * @param user login * @param server address/public void ConnectServer (STR ing server, String user, string password, string path) throws IOException {//SERVER:FTP server IP address; User: Logon to FTP server username   
      Password: The password of the username to log on to the FTP server; path:ftp the path on the server ftpclient = new FtpClient ();   
      Ftpclient.connect (server);  
      Ftpclient.login (user, password);
      int returnCode1 = Ftpclient.getreplycode ();
     SYSTEM.OUT.PRINTLN ("FTP Response code 1:" + returnCode1);  
          Path is a subdirectory of the home directory under the FTP service if (!ftpclient.changeworkingdirectory (path)) {//If you cannot enter Dir, this directory does not exist.
          System.out.println ("Path:" + path);
      Ftpclient.makedirectory (path); }//New set parameters//================================================================== Ftpclient.setbuffersize (
      1024);
      Ftpclient.setcontrolencoding ("UTF-8");
      Ftpclient.enterlocalpassivemode (); ================================================================== if (path.length ()!= 0) FtpClient.changeWorkin   
     Gdirectory (path); Upload and download ftpclient.setfile with 2Type (Binary_file_type);
      int returnCode2 = Ftpclient.getreplycode ();
SYSTEM.OUT.PRINTLN ("FTP Response code 1:" + returnCode2);           /** * Upload * upload file * @throws java.lang.Exception * @return-1 file does not exist *    
-2 File content is empty * >0 successfully uploaded, return file size * @param newname upload new filename * @param filename uploaded file * * *   
public boolean upload (String filename,string newname) throws Exception {long result = 0;   
      Telnetoutputstream OS = null;   
      FileInputStream is = null;
     Boolean flag = false;   
         try {java.io.File file_in = new java.io.File (filename);   
         if (!file_in.exists ()) return false;   
          /*if (File_in.length () ==0) return-2;   
          OS = Ftpclient.put (newname);   result = File_in.length ();   
        * * is = new FileInputStream (file_in);   
         /* byte[] bytes = new byte[1024];   
         int C; while ((c = is.read (bytes))!=-1) {os.write (bytes, 0, c);  
      } */flag = Ftpclient.storefile (New String (Newname.getbytes (), "iso-8859-1"), is);   
          Finally {if (is!= null) {is.close ();   
} return flag;
    public boolean uploadbytetoftp (String filename,byte pic[]) {Boolean flag = false;
    InputStream input = new Bytearrayinputstream (pic);
        try {flag = Ftpclient.storefile (New String (Filename.getbytes (), "iso-8859-1"), input);
          int returnCode1 = Ftpclient.getreplycode ();
    SYSTEM.OUT.PRINTLN ("FTP Response Code 3:" + returnCode1);
    catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
return flag; /** * Upload * @throws java.lang.Exception * @return * @param filename */public boolean upload (string filename) throws Exception {string newn   
    ame = "";   
     if (Filename.indexof ("/") >-1) {newname = filename.substring (Filename.lastindexof ("/") +1);   
     }else {newname = filename;   
return upload (filename,newname); /** * Download * download files from FTP to local * @throws java.lang.Exception * @return * @para M newfilename locally generated filename * @param filename on server filename *//*public long Download (String filename,string Newfil   
     ename) throws Exception {long result = 0;   
     Telnetinputstream is = null;   
    FileOutputStream OS = null;          
        try {is = ftpclient.get (filename);   
        Java.io.File outfile = new Java.io.File (newfilename);   
       OS = new FileOutputStream (outfile);   
       byte[] bytes = new byte[1024];   
       int C; while (c = IS.READ (bytes))!=-1) {os.write (bytes, 0, c);   
        result = result + C;   
     } catch (IOException e) {e.printstacktrace ();   
          Finally {if (is!= null) {is.close ();   
          } if (OS!= null) {os.close ();   
} return result; /** * Obtains all file lists in a directory * public list getfilelist (String path) {List List = new ArrayList   
    ();   
       try {datainputstream dis = new DataInputStream (ftpclient.namelist (path));   
       String filename = "";           
        while ((Filename=dis.readline ())!=null) {list.add (filename);   
     } catch (Exception e) {e.printstacktrace ();   
} return list; * * */** * closeserver * disconnected from the FTP server * @throws java.io.IOException/Public VOID CloseServer () throws IOException {try {if (ftpclient!= null) {   
       Ftpclient.disconnect ();   
    } catch (IOException e) {e.printstacktrace (); } public static string uploadfiletoftp (string IP, string user, string pass, String folder, String Pathandnam   
         E) throws exception{ftputil ftp = new Ftputil ();
         System.out.println ("Folder--->" + folder);
         String folderdate = folder + new SimpleDateFormat ("Yyyy-mm-dd"). Format (new Date ());

            System.out.println ("Folderdate--->" + folderdate);   
                 try {//Connect FTP server Ftp.connectserver (IP, user, pass, folderdate);
                  * * Upload files to the Info2 folder under *//*//Boolean flag = Ftp.upload ("D:/test.txt");
                  System.out.println ("Pathandname:" + pathandname);
                 Boolean flag = Ftp.upload (pathandname); 
                  if (flag) {System.out.println ("upload succeeded");
                  }else{System.out.println ("Upload failed");   
                } catch (Exception e) {///}finally {   
             Ftp.closeserver ();
           return folderdate;
        public static string Uploadbyte (String folder,string filename,string ip,string user,string pass,byte pic[]) {  
            Ftputil ftp = new Ftputil ();
            String folderdate = folder + new SimpleDateFormat ("Yyyy-mm-dd"). Format (new Date ());
        try {ftp.connectserver (IP, user, pass, folderdate);
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
        Boolean flag = false;
        Flag = ftp.uploadbytetoftp (filename, pic);
        
    return folderdate; public static void Main (String [] args)Throws Exception {ftputil ftp = new Ftputil (); try {//First Direct upload file//Connect FTP server Ftp.connectserver ("10.67.65.53", "Docuser", "Docuser", "/uat/   
          "+new SimpleDateFormat (" Yyyy-mm-dd "). Format (new Date ());
          * * Upload files to the Info2 folder *//*//upload file Boolean flag = Ftp.upload ("D:/test.txt");
          if (flag) {System.out.println ("upload succeeded");
          }else{System.out.println ("Upload failed");
          //second direct upload byte stream, FTP generated file F = new filename ("D:/test.txt");
          byte b[] = new byte[2048];
          InputStream input = new FileInputStream (f);  Note: The method of converting bytes into an input stream inputstream input = new Bytearrayinputstream (pic);
          Learn the juvenile Input.read (b);
          byte[] pic = b; String Datepath = Ftputil.uploadbyte ("/uat/", "fileName" + ". jpg", "10.67.65.53", "username", "password", pic
                
        
); System.out.println ("filEsize: "+ftp.upload (" d:/test.txt ") +" byte ");   
         /** gets the list of all files under the Info2 folder and downloads to e-disk under * *////////////* list = Ftp.getfilelist (".");   
             for (int i=0;i<list.size (); i++) {String filename = (String) list.get (i);   
             SYSTEM.OUT.PRINTLN (filename);   
          Ftp.download (filename, "e:/" +filename);   
     */} catch (Exception e) {///}finally {ftp.closeserver ();   }   
   }     
}



Finally, file creation is not able to create a multi-tiered directory, you must change the working directory, create a directory in the calling API

Related Article

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.