`
liaohanfeng
  • 浏览: 3643 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

ftp 连接

    博客分类:
  • ftp
阅读更多
package com.cmbstc.component.mgr.myLibrary.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class FtpServerTest {

/**
* ftp用户名
*/
String user = "Administrator";
/**
* 密码
*/
String password = "xiaofeng";
/**
* ip地址
*/
String server = "192.168.1.112";

// String user = "darviftp";
// String password = "darvi123";
// String server = "192.168.1.113";

public static void main(String[] args) {
FtpServerTest test = new FtpServerTest();
try {
// System.out.println(new FtpHandleUtil()
// .deleteFile("/results/20150321153100_20150321.xml"));
// 删除文档文件
// test.listDelete("/doc/");

// 上传文档文件
test.listUpload("G://showTime/xml//doc", "//doc//");

// // 上传xml通知文件文件
// long str = test.upload("G://showTime/xml//20150321.xml",
// "/xml/20150321.xml");
// System.out.println("上传:" + (str > 0 ? true : false));
//
// ftp下载文件
// long strs = test.download("/xml/20150321.xml",
// "G://showTime/xml//sss.xml");

// System.out.println("下载:" + (strs > 0 ? true : false));

// 时间设置 yyyyMMddhhmmss 2015(年)03月21日10时29分43秒
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// System.out.println(sdf.format(new Date()));
// // 根据当前Ftp的doc现有的文档 创建通知xml
// FtpModel model = new FtpModel();
// // // 设置上传的用户名
// model.setUserName("CMBSTC");
// // 设置文库创建时间
// model.setUploadDate("2015-03-21");
// test.createXMl("G:/showTime/xml/doc/", "G:/showTime/xml/"
// + sdf.format(new Date()) + ".xml", model);

// 查看ftp 的doc文档 跟本地文档
List<String> list = test.getFileNameListFTP("/doc/");
for (String s : list) {
System.out.println(s);
}
// System.out.println();
// File file = new File("G:showTime/xml/doc");
// for (int i = 0; i <file.list().length; i++) {
// System.out.println(file.list()[i]);
// }
//

} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
*/

/**
* 链接到Fpt服务器
*
* @return
*/
public FtpClient open() {
FtpClient ftpClient = null;
try {
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
ftpClient.binary();
} catch (Exception e) {
e.printStackTrace();
}
return ftpClient;
}

/**
* 链接到Fpt服务器
*
* @return
*/
public boolean open(FtpClient ftpClient) {
if (ftpClient != null) {
return true;
}
return false;
}

/**
* 从FTP服务器下载文件并返回下载文件长度
*
* @param ftpDirectoryAndFileName
*            :FTP服务器路径
* @param localDirectoryAndFileName
*            :下载文件后保存的路径
* @return
* @throws Exception
*/
public long download(String ftpDirectoryAndFileName,
String localDirectoryAndFileName) {
long result = 0;
// 创建ftp连接
FtpClient ftpClient = open();
if (!open(ftpClient))
return -2;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(ftpDirectoryAndFileName);
File file = new java.io.File(localDirectoryAndFileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
os = new FileOutputStream(file);
byte[] bytes = new byte[1024];
// 读取内容后再写入指定路径下的文件中
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
try {
if (is != null)
is.close();
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
return result;
}

/**
* 返回FTP目录下的文件列表
*
* @param ftpDirectory
*            (/doc/)
* @return
*/
@SuppressWarnings("deprecation")
public List<String> getFileNameListFTP(String ftpDirectory) {
List<String> list = new ArrayList<String>();
FtpClient ftpClient = null;
try {
ftpClient = open();
DataInputStream dis = new DataInputStream(ftpClient
.nameList(ftpDirectory));
String filename = "";
while ((filename = dis.readLine()) != null) {
filename = new String(filename.getBytes("ISO8859-1"), "GB2312");
list.add(filename);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return list;
}

/**
* upload 上传文件
*
* @throws java.lang.Exception
* @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
* @param newname
*            上传后的新文件名
* @param filename
*            上传的文件
*/
public long upload(String filename, String newname) {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
FtpClient ftpClient = null;
try {
ftpClient = open();
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
if (file_in.length() == 0)
return -2;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

/**
* 上传文件夹下的文件到ftp目录
*
* @param oldPath
*            (上传的文件夹路径 G:/showTime/)
* @param newPath
*            (Ftp的文件夹目录 /doc/)
*/
public void listUpload(String oldPath, String newPath) {
// 设置全局变量 (中文文件名支持)
System.setProperty("file.encoding", "GBK");
File file = new File(oldPath);
int i = 1;
for (String filePath : file.list()) {
// 上传
long str = upload(oldPath + "/" + filePath, newPath + filePath);
System.out.println(filePath + "--" + (str > 0 ? true : false));
i++;
}
}

/**
*
* 删除文件夹下的文件到ftp目录
*
* @param path
*            (/doc/)
*/
public void listDelete(String path) {
// 设置全局变量 (中文文件名支持)
System.setProperty("file.encoding", "GBK");
// 得到该目录下所有文件
List<String> list = getFileNameListFTP(path);
for (String fileName : list) {
System.out.println(fileName + "--" + ftpDelete(fileName));
}
}

/**
* 删除文件
*
* @param fc
*            FTP连接对象
* @param filename
*            删除的文件名称
* @return
*/
public boolean ftpDelete(String filename) {
FtpClient fc = null;
try {
fc = open();
fc.sendServer("dele " + filename + "\r\n");
fc.readServerResponse();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 随机产生文档简介
*
* @return 简介
*/
public String fileDesc() {
int number = 1;
try {
// 1 2 3 4
number = new Random().nextInt(4) + 1;
} catch (Exception e) {
e.printStackTrace();
}
String[] descString = {
"",
"简介........",
"那家伙很懒........",
"我是简介.......",
"unable to, be unable to, unable to speak, be unable to breathe, unable to move, be unable" };
return descString[number];
}

public List<String> getDocNameList(String path) {
List<String> list = new ArrayList<String>();
try {
File file = new File(path);
// 创建file数组用来存储数据
File[] filArr = file.listFiles();
for (int i = 0; i < filArr.length; i++) {
list.add(filArr[i].getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}

/**
* 根据当前文件夹的现有的文档 创建通知xml
*
* @param docFolderPath
*            doc文件夹
* @param xmlPath
*            xml存放路径
* @param model
*            xml内容
* @return
*/
public boolean createXMl(String docFolderPath, String xmlPath,
FtpModel model) {
try {
List<String> list = getDocNameList(docFolderPath);
model.setCount(list.size() + "");
List<FtpModel> fileList = new ArrayList<FtpModel>();
for (String str : list) {
FtpModel file = new FtpModel();
String[] fileName = str.split("\\\\");
String fileTitle = (fileName[fileName.length - 1]).replaceAll(
"[.][^.]+$", "");
file.setFileTitle(fileTitle);
file.setFileDesc(fileDesc());
file.setFilePath("/doc/" + fileName[fileName.length - 1]);
File fileSize = new File(str);
file.setFileSize(fileSize.length() + "");
fileList.add(file);
}
model.setFileList(fileList);
exportXML(xmlPath, model);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
*
* @title exportXML 生成结果xml
* @param path
* @param docObject
* @throws IOException void
*/
public static int exportXML(String path, FtpModel docObject)
throws IOException {
try {
// 创建根节点 list;
Element root = new Element("xml");
// 根节点添加到文档中;
Document Doc = new Document(root);
// 创建节点 并赋text值
root.addContent(new Element("users").setText(docObject
.getUserName()));
root.addContent(new Element("count").setText(docObject.getCount()));
root.addContent(new Element("uploaddate").setText(docObject
.getUploadDate()));
Element root1 = new Element("filelist");
root.addContent(root1);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i < docObject.getFileList().size(); i++) {
// 创建节点 file;
Element elements = new Element("file");
FtpModel doc = docObject.getFileList().get(i);
// 创建节点 并赋text值
elements.addContent(new Element("filetitle").setText(doc
.getFileTitle()));
elements.addContent(new Element("filepath").setText(doc
.getFilePath()));
elements.addContent(new Element("filedesc").setText(doc
.getFileDesc()));
elements.addContent(new Element("filesize").setText(doc
.getFileSize()));
// 给父节点list添加user子节点;
root1.addContent(elements);
}
// 设置头部编码
XMLOutputter XMLOut = new XMLOutputter(Format.getPrettyFormat()
.setEncoding("utf-8"));
// 设置输出流 并设置编码格式
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(path), "utf-8");
// 输出XML
XMLOut.output(Doc, writer);
// 关闭流
writer.close();
return 0;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
}

class FtpModel implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

private String id; // id标示

private String fileName; // 文档名称

private String count; // 文档个数

private Integer userId; // 用户id

private String userName;// 用户名

private String fileTitle; // 文库标题

private String fileSize; // 文档大小(字节)

private String filePath; // 文档路径

private String fileDesc; // 文档简介

private String uploadDate;// 上传时间

private String fileSuccess;// 文档上传成功数

private String fileError;// 文档上传失败数

private String handleDate;// 处理时间

private String errorId; // 我是错误编号

private String message;// 错误信息日志

private List<FtpModel> fileList = new ArrayList<FtpModel>(); // 文档集合

public FtpModel() {

}

public FtpModel(String fileTitle, String fileSize, String filePath,
String errorId, String message) {
this.fileTitle = fileTitle;
this.fileSize = fileSize;
this.filePath = filePath;
this.errorId = errorId;
this.message = message;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getFileSize() {
return fileSize;
}

public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public String getFileDesc() {
return fileDesc;
}

public void setFileDesc(String fileDesc) {
this.fileDesc = fileDesc;
}

public String getUploadDate() {
return uploadDate;
}

public void setUploadDate(String uploadDate) {
this.uploadDate = uploadDate;
}

public List<FtpModel> getFileList() {
return fileList;
}

public void setFileList(List<FtpModel> fileList) {
this.fileList = fileList;
}

public String getCount() {
return count;
}

public void setCount(String count) {
this.count = count;
}

public String getFileSuccess() {
return fileSuccess;
}

public void setFileSuccess(String fileSuccess) {
this.fileSuccess = fileSuccess;
}

public String getFileError() {
return fileError;
}

public void setFileError(String fileError) {
this.fileError = fileError;
}

public String getHandleDate() {
return handleDate;
}

public void setHandleDate(String handleDate) {
this.handleDate = handleDate;
}

public String getErrorId() {
return errorId;
}

public void setErrorId(String errorId) {
this.errorId = errorId;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getFileTitle() {
return fileTitle;
}

public void setFileTitle(String fileTitle) {
this.fileTitle = fileTitle;
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics