java ftp 上传源码

package com.test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;

public class FTPTest {
 /**
  *
  * @param webname
  */
 public static void uploadReviewHC(String webname){
  FTPClient ftpClient = new FTPClient();
  String servername = "192.168.119.169";//ftp服务器
  String port = "21";//端口
  String username = "zrtest";//用户名称
  String passwd = "asdfgh";//密码
  String localFilePath = "F://ReviewHC//index.htm";//需要上传的本地文件
  String reviewDir = "ReviewHC";//ftp服务端目录
  try {
   ftpClient.connect(servername, Integer.parseInt(port));
   /** 设置超时时间 */
   ftpClient.setDataTimeout(18000);
   ftpClient.login(username, passwd);
   // 1,先创建目录--以新行业的webname 为名称
   boolean flag = createDirectory(ftpClient, webname);
   // 2。创建ReviewHC
   if (flag) {
    ftpClient.changeWorkingDirectory("/" + webname);
    if (createDirectory(ftpClient, reviewDir)) {
     ftpClient.changeWorkingDirectory("/" + webname + "/"+ reviewDir + "/");
     BufferedInputStream buff = new BufferedInputStream(new FileInputStream(localFilePath));
     ftpClient.enterLocalPassiveMode();
     boolean sult = ftpClient.storeFile("index.htm", buff);
     if (sult) {
      System.out.println("上传成功!");
     } else {
      System.out.println("上传失败");
     }
    }

   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally{
   try {
    ftpClient.logout();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  
 }

 /**
  * 创建文件夹
  *
  * @param ftpClient
  * @param dirName
  */
 public static boolean createDirectory(FTPClient ftpClient, String dirName) {
  try {
   boolean f = ftpClient.changeWorkingDirectory(dirName);
   if (!f) {// 不存在此目录
    boolean f2 = ftpClient.makeDirectory(dirName);
    System.out.println("创建" + dirName + "  " + f2);
    return f2;
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return true;
 }

 public static void main(String[] args) {
  try {
   uploadReviewHC("zr");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值