多线程查询FTP Server上的文件

时间:2023-03-09 15:48:15
多线程查询FTP Server上的文件

情形是这样的,最近做一个自动化的项目,当batch跑成功了,FTP Server上会有特定的生成文件。但是不确定是什么时候会有,大概是batch跑完了5分钟之内吧,所以在脚本里设置检查点的时候,需要每隔一段时间去刷新FTP Server上的文件。

网上下了个Serv-U去搭建了个本地的FTP Server,很容易就搭建调试好。然后又下了个commons-net-3.3.jar包去处理FTP相关的业务。

或许可以不需要用多线程,但是试了下,单线程的去退出再重新登录到FTP Server,FTP Server上的文件并不会自动刷新。所以我在main函数里,每隔一段时间就启动一个线程去看看我要找的文件是否存在。

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; public class FTPUtil extends Thread {
private FTPClient ftpClient = new FTPClient();
private String ftpdict = ".";
private boolean flag;
private static boolean find = false;
private static long timeslot = 10000; public boolean connect(String host, int port, String username,
String password) throws IOException {
ftpClient.connect(host, port);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(username, password)) {
return true;
}
}
ftpClient.disconnect();
return false;
} public boolean fileExist(String dict, String filename) {
String pattren = "\\.{1,}";
ftpdict = ftpdict + "/" + dict;
try {
FTPFile[] files = ftpClient.listFiles(ftpdict);
for (int i = 0; i < files.length; i++) {
if (files[i].getName().equalsIgnoreCase(filename)) {
flag = true;
}
if (files[i].isDirectory()
&& !files[i].getName().matches(pattren)) {
fileExist(files[i].getName(), filename);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
} public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} public void run() {
System.out.println(getName() + " thread started!");
FTPUtil ftp = new FTPUtil();
try {
ftp.connect("127.0.0.1", 21, "admin", "admin");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean b = ftp.fileExist(ftp.ftpdict, "3.txt");
System.err.println(b);
if (b) {
find = true;
}
try {
ftp.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getName() + " thread ended!");
} @SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int index = 0;
while (!find) {
new FTPUtil().start();
Thread.currentThread().sleep(timeslot);
if (index == 4) {
return;
}
index++;
}
}
}

我觉得应该有api是去刷新这个FTP Server的,暂时还没有摸索到,有知道的告知一声谢谢咯。