import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import com.hikvision.cms.modules.crossing.domain.UploadParameter;
import com.hikvision.cms.scaffolding.util.string.StringUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
*
*
* @author 2012-6-14 上午10:21:46
* @version V1.0
* @modificationHistory=========================逻辑或功能性重大变更记录
* @modify by user: {修改人} 2012-6-14
* @modify by reason:{方法名}:{原因}
*/
public class AppcheFTP {
private static Logger logger = Logger.getLogger(AppcheFTP.class);
private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();//http下载支持多线程
private static HttpClient client = new HttpClient(connectionManager);
/**
* 连接登录FTP服务器,获取ftp对象
* @author 刘卓 2012-6-15 上午11:20:43
* @param ipAddr
* @param port
* @param username
* @param password
* @return
*/
public static FTPClient login(String ipAddr, int port, String username, String password) {
FTPClient client = new FTPClient();
try {
client.setConnectTimeout(1800000);// 设置超时时间
client.connect(ipAddr, port);// 连接ftp
client.login(username, password);// 登录ftp
if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
// 设置编码,避免中文乱码
client.setControlEncoding("GBK");
FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_NT);
config.setServerLanguageCode("zh");
client.setFileType(FTPClient.BINARY_FILE_TYPE);//设置2进制传输
logger.info("FTP连接成功。");
return client;
} else {
logger.info("未连接到FTP,用户名或密码错误。");
client.disconnect();
}
} catch (SocketException e) {
logger.info("FTP的IP地址可能错误,请正确配置。" + e.getMessage());
// TODO: handle exception
} catch (IOException e) {
// TODO: handle exception
logger.info("FTP的端口错误,请正确配置。" + e.getMessage());
}
return null;
}
/**
* 检查文件夹是否存在
* @param dir
* @param ftpClient
* @return
*/
public static Boolean isDirExist(String dir, FTPClient ftpClient) {
try {
ftpClient.changeWorkingDirectory(dir);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
return true;
}
/**
* 遍历ftp指定路径下的文件夹
* @author 2012-6-15 上午11:30:28
* @param client
* @param pathName
* @param ext
* @param idexsString
* @param arFiles
* @throws IOException
*/
public static void List(FTPClient client, String pathName, String ext, String idexsString, List<String> arFiles)
throws IOException {
if (pathName.startsWith("/") && pathName.endsWith("/")) {
String directory = pathName;
// 更换目录到当前目录
client.changeWorkingDirectory(directory);
FTPFile[] files = client.listFiles();
for (FTPFile file : files) {
if (file.isDirectory()) {//如果是目录
if (!file.getName().equals(".") && (!file.getName().equals(".."))) { // 注意这里的判断,否则会出现死循环!!!!
if (idexsString.indexOf(file.getName()) > -1 && file.getName().length() == 10) {
arFiles.add(directory + file.getName());
}
List(client, directory + file.getName() + "/", ext, idexsString, arFiles);//遍历
}
}
}
client.changeToParentDirectory();
}
}
/**
* 读取指定文件夹下的inf文件
* @author 2012-6-15 上午11:35:58
* @param ftpClient
* @param ftpPath
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static String readConfigFileForFTP(FTPClient ftpClient, String ftpPath) throws UnsupportedEncodingException, Exception {
StringBuffer resultBuffer = new StringBuffer();
try {
ftpClient.changeWorkingDirectory(ftpPath);
FTPFile[] fs = ftpClient.listFiles();
System.out.println(fs.length);
for (FTPFile file : fs) {
InputStream in = null;
if (file.isFile() && file.getName().endsWith("inf")) {
ftpClient.enterLocalPassiveMode();
in = ftpClient.retrieveFileStream(file.getName());
ftpClient.completePendingCommand();
if (in != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
String data = null;
try {
while ((data = br.readLine()) != null) {
resultBuffer.append(data + "\n");
}
resultBuffer.append("&" + ftpPath+",");
br.close();
} catch (IOException e) {
logger.error("文件读取错误。"+e.getMessage());
e.printStackTrace();
return null;
}
} else {
logger.error("in为空,不能读取。");
return null;
}
try {
if (null != in) {
in.close();
}
// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
System.out.println("---------" + ftpClient.getReplyCode());
if (ftpClient.getReplyCode() == 226) {
//ftpClient.getReply();
}
} catch (Exception e2) {
logger.error("错误"+e2.getMessage());
}
}
}
} catch (FileNotFoundException e) {
return null;
} catch (SocketException e) {
logger.error("连接FTP失败."+e.getMessage());
//e.printStackTrace();
} catch (IOException e) {
logger.error("读取文件错误"+e.getMessage());
return null;
}
return resultBuffer.toString();
}
/**
* 在服务器上创建一个文件夹
* @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
* @throws IOException
*/
public static boolean makeDirectory(String dir,FTPClient ftpClient) throws IOException {
boolean flag = true;
flag = ftpClient.makeDirectory(dir); //创建文件夹
if (flag) {
logger.error("创建文件夹" + new String(dir.getBytes("iso-8859-1"), "GBK") + " 成功");
} else {
logger.error("创建文件夹" + new String(dir.getBytes("iso-8859-1"), "GBK") + " 失败");
}
return flag;
}
/**
* 从图片服务器下载图片
* @author 2012-5-7 下午03:37:06
* @param httpAddr
* @return
* @throws Exception
*/
public static byte[] downLoadPicture(String httpAddr){
GetMethod get = null;
try {
get = new GetMethod(httpAddr);
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
client.executeMethod(get);
} catch (HttpException e) {
logger.info("连接图片服务器异常。");
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
return null;
} catch (IOException e) {
logger.info("连接图片服务器异常。");
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
return null;
}
byte[] data = null;
try {
data = get.getResponseBody();
} catch (IOException e) {
logger.info("下载图片异常。");
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
return null;
}
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
return data;
}
/**
*
* 关闭FTP服务
* @param ftpClient
* 客户端
* @throws IOException
*
*/
public static void closeFTPClient(FTPClient ftpClient) throws IOException {
if (ftpClient != null)
ftpClient.disconnect();
}
//判断是否有该文件
private static boolean pdFile(String filename,FTPClient ftpClient) throws IOException{
boolean flag=false;
String filenameString = new String(filename.getBytes("GBK"),"iso-8859-1");
if(ftpClient.isConnected()){
try{
FTPFile[] file=ftpClient.listFiles(filenameString);
if(file.length>0){
flag=true;
}
}catch (Exception e) {
// TODO: handle exception
}
}
return flag;
}
/**
* 上传文件
* @author 2012-7-12 下午02:14:27
* @param filename
* @param input
* @param ftpClient
* @return
* @throws Exception
*/
public static int upLoadFile(String filename,InputStream input,FTPClient ftpClient) throws Exception{
int i=0;
String filenameString = new String(filename.getBytes("GBK"),"iso-8859-1");//转码
if(ftpClient.isConnected()){
ftpClient.enterLocalPassiveMode();
try{
ftpClient.storeFile(filenameString, input);
}
catch (Exception e) {
// TODO: handle exception
logger.error("上传"+filename+"失败:",e);
i=1;
}
}else{
logger.error("未连接FTP服务器");
i=2;
}
return i;
}
public static String changTotimeString(String str){
StringBuffer stringBuffer = new StringBuffer();
if(StringUtil.isNotNullOrEmpty(str)){
String temp = str.substring(10, str.length()-1);
stringBuffer.append(temp.substring(0, 4)+"-"+temp.substring(4,6)+"-"+temp.substring(6,8));
stringBuffer.append(" "+temp.substring(8, 10)+":"+temp.substring(10, 12)+":"+temp.substring(12, 14)+":"+temp.substring(14, temp.length()));
}
return stringBuffer.toString();
}
/**
* 读取xml配置文件
* @author 2012-7-12 下午02:15:53
* @return
*/
public static UploadParameter readXmlConfig(){
Document configDoc = null;
String defaultPath = "";
try {
defaultPath = URLDecoder.decode(XmlUtil.class.getResource("/")
.getFile()
+ "upLoadVehiclealarmdata.xml", "gbk");
} catch (UnsupportedEncodingException e) {
logger.error("文件路径转码失败!", e);
}
SAXBuilder sb = new SAXBuilder();
try {
configDoc = sb.build("file:///"+defaultPath);//如果是中文路径,必须加file:///
} catch (Exception e) { // 构造文档对象
logger.error("xml文件读取失败!", e);
}
Element root = configDoc.getRootElement(); // 获取根元素
Element enable = root.getChild("EnableTask");
UploadParameter uploadParameter = new UploadParameter();
uploadParameter.setEnableTask(enable.getText().equals("true"));
uploadParameter.setFtpIP(root.getChild("ftpIP").getText());
uploadParameter.setFtpPort(root.getChild("ftpPort").getText());
uploadParameter.setUsername(root.getChild("userName").getText());
uploadParameter.setDbPasswd(root.getChild("passWd").getText());
return uploadParameter;
}
/**
* 压缩图片到固定的尺寸
* @author 2012-7-26 下午01:55:42
* @param inputStream
* @param width
* @param height
* @return
*/
public static ByteArrayInputStream imageScale(InputStream inputStream, int width, int height) {
try {
Image image = javax.imageio.ImageIO.read(inputStream); //从输入流读取图片
image = image.getScaledInstance(width, height,
Image.SCALE_FAST);
BufferedImage mBufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
mBufferedImage.getGraphics().drawImage(
image, 0, 0, null);
OutputStream out = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); //以流的方式输出图片
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(mBufferedImage);
param.setQuality(0.5f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(mBufferedImage);
/**
* 将outputStream 转为inputStream
*/
ByteArrayOutputStream baos=new ByteArrayOutputStream();
baos=(ByteArrayOutputStream) out;
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray()); //将输出流转为输入流
out.close(); //关闭流
out=null;
return swapStream;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
try{
String server = "10.64.52.15";
String user = "admin";
String passWord = "12345";
System.out.println("begin connect!");
FTPClient ftpClient = AppcheFTP.login("10.64.52.15", 21, "admin", "12345");
System.out.println("connect success!");
try{
// 设置编码,避免中文乱码
String savefilename = new String("20110101".getBytes("GBK"),"iso-8859-1");
if(ftpClient.changeWorkingDirectory(savefilename)){
System.out.println("weee");
}else{
AppcheFTP.makeDirectory(savefilename, ftpClient);
}
//createDir(savefilename,ftpClient);
}catch (Exception e) {
e.printStackTrace();
}
AppcheFTP.closeFTPClient(ftpClient);
System.out.println("close success!");
}catch(UnknownHostException e){
System.out.println("java.net.UnknownHostException");
}catch(IOException e){
System.out.println("test!");
}
}
Apache FTP操作
最新推荐文章于 2021-08-06 04:05:09 发布