最近研究FTP,发现FTP对远程文件读取资源各方都比较片面,自己写了一个FTPutil,保留一下
FTP服务器:所有的都行,我这里找了一个小型的附件有
FTP文件目录:ftp根目录下:beifen文件夹,ceshi文件夹
FTP配置文件:a.properties,放在WEB-INF目录下
a.properties内容:
ip = 127.0.0.1
userName = meibin
userPwd = 123456
port = 21
path = E:/ftp
package test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.coyote.OutputBuffer;
import test1.PropertyTest;
/**
* @describe FTP操作
* @auto meibin
* @date 2017-04-20
*/
public class FtpUtils {
private FTPClient ftpClient;
private String ip ; // 服务器IP地址
private String userName; // 用户名
private String userPwd; // 密码
private int port; // 端口号
private String path; // 读取文件的存放目录
private String remoteDir = "/";
/**
* init ftp servere
*/
public FtpUtils() {
this.reSet();
}
public void reSet() {
Properties prop = new Properties();
String paths = PropertyTest.class.getResource("/").getPath();
String websiteUrl = paths.replace("/build/classes", "").replace("%20",
" ")
+ "/WebContent/WEB-INF/a.properties";
try{ //读取属性文件a.properties
InputStream in = new BufferedInputStream (new FileInputStream(websiteUrl));
prop.load(in); ///加载属性列表
Iterator
ip=prop.getProperty("ip");
userName=prop.getProperty("userName");
userPwd=prop.getProperty("userPwd");
port=Integer.parseInt(prop.getProperty("port"));
path = prop.getProperty("path");
in.close();
}catch (Exception e) {
}
this.connectServer(ip, port, userName, userPwd, path);
}
/**
* @param ip
* @param port
* @param userName
* @param userPwd
* @param path
* @throws SocketException
* @throws IOException
* function:连接到服务器
*/
public void connectServer(String ip, int port, String userName,
String userPwd, String path) {
ftpClient = new FTPClient();
try {
// 连接
ftpClient.connect(ip, port);
// 登录
ftpClient.login(userName, userPwd);
if (path != null && path.length() > 0) {
// 跳转到指定目录
ftpClient.changeWorkingDirectory(path);
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @throws IOException
* function:关闭连接
*/
public void closeServer() {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* 获取以当前时间命名的文件夹名字
*/
public String getTimeFilename() {
Calendar c = Calendar.getInstance();
Integer year = c.get(Calendar.YEAR);
Integer month = c.get(Calendar.MONTH)+1;
Integer data = c.get(Calendar.DATE);
String paths;
if (month.toString().length() == 1) {
return paths = Integer.toString(year)+"0"+Integer.toString(month)+Integer.toString(data);
} else {
return paths = Integer.toString(year)+Integer.toString(month)+Integer.toString(data);
}
}
/**
* @param path
* @return function:读取指定目录下的文件名
* @throws IOException
*/
public List
List
// 获得指定目录下所有文件名
FTPFile[] ftpFiles = null;
try {
String paths = this.getTimeFilename();
ftpClient.changeWorkingDirectory("ceshi/"+paths+"/"+filenamen+"/");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpFiles = ftpClient.listFiles(path);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
FTPFile file = ftpFiles[i];
if (file.isFile()) {
fileLists.add(file.getName());
}
}
return fileLists;
}
/*
* 取得第一层文件目录
*/
public List
List
// 获得指定目录下所有文件名
FTPFile[] ftpFiles = null;
try {
String paths = this.getTimeFilename();
ftpClient.changeWorkingDirectory("ceshi/"+paths+"/");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpFiles = ftpClient.listFiles(path+"/"+paths+"/");
System.out.println("..............");
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
FTPFile file = ftpFiles[i];
fileLists.add(file.getName());
System.out.println(file.getName());
}
return fileLists;
}
/*
* 取得单个文件文件名
*/
// public String getFileName() {
// String fileNames = null;
// List
// for (int i = 0; i < fileList.size(); i++) {
// return fileNames = fileList.get(i);
// }
// return fileNames;
// }
/**
* 写入文件,简单实现
*/
public boolean setFile(String test){
InputStream inputStream = new ByteArrayInputStream(test.getBytes());
try {
ftpClient.storeFile("ceshi.txt", inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* @param fileName
* @return function:从服务器上读取指定的文件
* @throws ParseException
* @throws IOException
*/
public String readFile() throws ParseException {
InputStream ins = null;
StringBuilder builder = null;
String ceshi = "/ceshi/";
String paths = this.getTimeFilename();
try {
// 从服务器上读取指定的文件
List
String fileNamen;
for (int j = 0; j < fileListn.size(); j++) {
fileNamen = fileListn.get(j);
String fileNames;
//调用getFileList方法,传入当前路径,由于在方法中需要更换目录,所以把当前所在组合名称文件夹名字也传过去
List
//遍历当前文件夹下所有文件
for (int i = 0; i < fileList.size(); i++) {
fileNames = fileList.get(i);//当前文件名字
ftpClient.enterLocalPassiveMode();//更改输入模式
ftpClient.changeWorkingDirectory(fileNamen);//进入当前目录
ins = ftpClient.retrieveFileStream(fileNames);//读取文件
BufferedReader reader = new BufferedReader(
new InputStreamReader(ins, "UTF-8"));
String line;
builder = new StringBuilder(150);
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
reader.close();
if (ins != null) {
ins.close();
}
// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
ftpClient.getReply();
//更换到备份目录
ftpClient.changeWorkingDirectory("../../../beifen");
//创建目录,如果已有文件会返回falese, 这里应该加个判断,但返回false并不影响执行,所以没有处理
ftpClient.makeDirectory(paths);
//进入paths目录
ftpClient.changeWorkingDirectory(paths);
//同上
ftpClient.makeDirectory(fileNamen);
//返回文件所在文件夹
ftpClient.changeWorkingDirectory("../../ceshi/"+paths+"/"+fileNamen);
String aString = "../../../beifen/"+paths+"/"+fileNamen+"/"+fileNames;//当前文件目录
//如果是当前文件夹最后一个文件,在移除文件后,就会返回上一层,并删除此文件夹,如果不是就只移除文件
if (i>=fileList.size()-1) {
ftpClient.rename(fileNames,aString);//移除文件
ftpClient.changeWorkingDirectory("../");
ftpClient.removeDirectory(fileNamen);
}else {
ftpClient.rename(fileNames, aString);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
/**
* @param args
* @throws ParseException
*/
// public static void main(String[] args) throws ParseException {
// FtpUtils ftp = new FtpUtils();
// String str = ftp.readFile();
// System.out.println(str);
// }
public static void main(String[] args) {
TimerTask task = new TimerTask() {
public void run() {
try {
FtpUtils ftp = new FtpUtils();
ftp.readFile();
} catch (Exception e) {
}
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 4 * 1000;
timer.scheduleAtFixedRate(task, delay, intevalPeriod);
// FtpUtils ftpUtils = new FtpUtils();
// String test = "zheshiyigeceshi1";
// ftpUtils.setFile(test);
}
}