投稿‎ > ‎

FTPUtilsGet.java

posted Jun 14, 2016, 6:43 PM by Zhang Wenxu   [ updated Jun 19, 2016, 5:16 PM ]
package jp.btsol.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtilsGet{
    public static void main(String[] arg) throws Exception{
       Option optServer = OptionBuilder.withLongOpt("server").withDescription("ftp server").hasArg().withArgName("server").create('s');
       Option optUser = OptionBuilder.withLongOpt("user").withDescription("ftp user").hasArg().withArgName("user").create('u');
       Option optPassword OptionBuilder.withLongOpt("password").withDescription("ftp password").hasArg().withArgName("password").create('p');
       Option optRemoteFile = OptionBuilder.withLongOpt("remoteFile").withDescription("remote file to be get from server").hasArg().withArgName("file").create('f');
       Option optLocalDir = OptionBuilder.withLongOpt("localDir").withDescription("local die to accept remote file").hasArg().withArgName("dir").create('d');
       Options opts = new Options();
        opts.addOption(optServer).addOption(optUser).addOption(optPassword).addOption(optRemoteFile).addOption(optLocalDir);
       HelpFormatter h = new HelpFormatter();
       h.printHelp("FTPUtilsGet [opts]", opts);
       CommandLineParser parser = new GnuParser();
       CommondLine cl = null;
       try{
            cl = parser.parse(opts, arg, true);
       }
       catch(ParseExcepion e){
            e.printStackTrace();
            return;
      }
      FileOutputStream os = null;
      FTPClient fp = new FTPClient();
      try{
           fp.connect(cl.getOptionValue("s", "192.168.1.10"));
           if(!FTPReply.isPositiveCompletion(fp.getReplyCode())){
                 System.exit(1);
           }
           if(fp.login(cl.getOptionValue("u", "user"), cl.getOptionValue("p", "password")) == false){
                 System.exit(1);
           }
           fp.setFileType(FTP.BINARY_FILE_TYPE);
           os = new FileoutputStream(cl.getOptionValue("d") + File.separatorChar + FilenameUtils.getName(cl.getOptionValue("f")));
           fp.retriveFile(cl.getOptionValue("f"), os);
           os.close();
      }
      catch(Exception e){
          e.printStackTrace();
      }
      finally{
          fp.disconnect();   
          os.close();
      }
}
Comments