投稿‎ > ‎

FTPUtilsPut.java

posted Jun 15, 2016, 2:07 AM by Zhang Wenxu
package jp.btsol.ftp;

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 FTPUtilsPut{
    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 optLocalFile = OptionBuilder.withLongOpt("localFile").withDescription("local file to be put to server").hasArg().withArgName("file").create('f');
       Option optRemoteDir = OptionBuilder.withLongOpt("remoteDir").withDescription("remote dir to accept local 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("FTPUtilsPut [opts]", opts);
       CommandLineParser parser = new GnuParser();
       CommondLine cl = null;
       try{
            cl = parser.parse(opts, arg, true);
       }
       catch(ParseExcepion e){
            e.printStackTrace();
            return;
      }
      FileInputStream is = null;
      FTPClient fp = new FTPClient();
      try{
           fp.connect(cl.getOptionValue("server", "192.168.1.10"));
           if(!FTPReply.isPositiveCompletion(fp.getReplyCode())){
                 System.exit(1);
           }
           if(fp.login(cl.getOptionValue("user", "user"), cl.getOptionValue("password", "password")) == false){
                 System.exit(1);
           }
           fp.setFileType(FTP.BINARY_FILE_TYPE);
           is = new FileinputStream(cl.getOptionValue("f"));
           fp.storeFile(cl.getOptionValue("d") + File.separatorChar + FilenameUtils.getName(cl.getOptionValue("f")), is);
           is.close();
      }
      catch(Exception e){
          e.printStackTrace();
      }
      finally{
          fp.disconnect();   
          is.close();
      }
}
Comments