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();
}
}
}