FTP Upload Download Tool class

Source: Internet
Author: User
Tags ftp
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;

Import java.net.SocketException;
Import org.apache.commons.net.ftp.FTPClient;
Import Org.apache.commons.net.ftp.FTPFile;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory; /** * @khj * @title ftputils * @Description: FTP upload Download Tool class * @time */public class Ftputils {/** * log *
    
    /private static Logger Logger = Loggerfactory.getlogger (Ftputils.class);
    
    private static ftpclient ftp;
     /** * Connect FTP < A word function description > < function details > * * @param addr * @param port * @param username * @param password * @return * @see [Class, Class # method, Class # Member] */public static Boolean connect (String addr, int port
        
        , string Username, string password) {ftp = new ftpclient (); try {FTP. Connect (addr, 21);
            
        Ftp.login (username, password);
        } catch (SocketException e) {e.printstacktrace ();
        } catch (IOException e) {e.printstacktrace ();
    } return ftp.isconnected (); } @SuppressWarnings ("unused") private void upload (file file, String path) {logger.info ("file.is
        
        Directory (): {} "+ file.isdirectory ());
                try {if (File.isdirectory ()) {ftp.makedirectory (File.getname ());
                Ftp.changeworkingdirectory (File.getname ());
                string[] files = file.list (); for (int i = 0; i < files.length; i++) {File File1 = new File (File.getpath () + "\ \
                    "+ files[i]);
                        if (File1.isdirectory ()) {upload (file1, path); Ftp.changetopareNtdirectory (); } else {file File2 = new File (File.getpath () + "\ \" + fil
                        Es[i]);
                        FileInputStream input = new FileInputStream (file2);
                        Ftp.storefile (File2.getname (), input);
                    Input.close ();
                
                }}} else {file File2 = new File (File.getpath ()); System.out.println ("File.getpath ():" + file.getpath () + "|
                
                File2.getname (): "+ file2.getname ());
                
                InputStream input = new FileInputStream (file2);
                Ftp.changeworkingdirectory (path);
                
                Ftp.storefile (File2.getname (), input); Input.close (); Close the input stream ftp.logout (); Exit Connection}} catch (Exception e) {logger.erRor (E.getmessage ()); }} @SuppressWarnings ("static-access") public static byte[] DownloadFile (String fileName) {b
        yte[] bytes = NULL;
            
            try {ftp.changeworkingdirectory ("");
            
            List all files under this directory ftpfile[] fs = Ftp.listfiles (FileName);
                Traverse all files to locate the specified file for (Ftpfile file:fs) {if (File.getname (). Equals (FileName))
                    {///files LocalFile = new file (LocalPath) according to absolute path initialization;
                    if (!localfile.exists ())//{//Localfile.createnewfile (); 
                    }/////output stream//outputstream OS = new FileOutputStream (localfile);
                    InputStream in = null;
                    Download file ftp.setbuffersize (1024); Ftp.setcontrolencoding ("UTF-8 ");
                    Ftp.setfiletype (Ftp.binary_file_type);
                    
                    Download files to LocalFile//Ftp.retrievefile (Ff.getname (), OS);
                    String remoteabsolutefile = File.getname ();
                    Remoteabsolutefile = new String (remoteabsolutefile.getbytes ("UTF-8"), "iso-8859-1");
                    
                    in = Ftp.retrievefilestream (Remoteabsolutefile);
                
                    bytes = Input2byte (in);
                    
                    System.out.println ("Download succeeded!" + bytes.length);
                In.close (); }} ftp.logout ();
        Exit connection} catch (Exception e) {e.printstacktrace ();
    } return bytes; }/** * byte[] go to file * * @param bytes * @param path * @return * @see [Class, Class # method, Class # into */public static void Bytetofile (byte[] bytes, String path) {try {//] Initialize file LocalFile = new (path) according to Absolute path;
            if (!localfile.exists ()) {localfile.createnewfile ();
            
            }//output stream OutputStream OS = new FileOutputStream (localfile);
            
            Os.write (bytes);
        Os.close ();
        } catch (Exception e) {e.printstacktrace ();
     }}/** * file to byte[] < A word function description > < function details > * * @param instream * @return
        * @throws IOException * @see [Class, Class # method, Class # Member] */public static byte[] Input2byte (InputStream instream)
        Throws IOException {Bytearrayoutputstream Swapstream = new Bytearrayoutputstream ();
        byte[] buff = new byte[100];
        int rc = 0;
        while (rc = instream.read (buff, 0,)) > 0) {swapstream.write (buff, 0, RC); } byte[] in2b = Swapstream.tobytearray ();
        
        Swapstream.close ();
    return in2b; } public static void Getphoto (String filepath,string localPath) {ftputils.connect (readpropertiesutil S.getparamvalue ("Ftp.host"), +, Readpropertiesutils.getparamvalue ("Ftp.username"), Re
        Adpropertiesutils.getparamvalue ("Ftp.password"));
        Logger.info ("");
        
        byte[] bytes = Ftputils.downloadfile (FilePath);
    Ftputils.bytetofile (bytes, localPath); } public static byte[] Getphoto (String filePath) {ftputils.connect (readpropertiesutils.getparamvalue ("Ftp.host"), Readpropertiesutils.getparamvalue ("Ftp.username"), Readpropertiesuti
        Ls.getparamvalue ("Ftp.password"));
        Logger.info ("");
        
        byte[] bytes = Ftputils.downloadfile (FilePath);
        Ftputils.bytetofile (bytes, localPath);
    return bytes;
    
    }public static void Main (string[] args) throws Exception {String FilePath = "T_zdry_idx_jxxx_
        
        Inc/010020090902731604.jpg ";
        
        String LocalPath = "D:\\ccc.jpg";
    Ftputils.getphoto (FilePath, LocalPath);
 }
}

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.