Java判断本地文件夹是否存在
File localFile = new File(*文件路径*);
if (!localFile.exists() && !localFile.isDirectory()){
//执行操作
}
Java判断FTP是否连接成功
public void connectFTP(String hostname, int port, String username, String password) {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
ftpClient.connect(hostname, port); //连接到FTP服务器,若报错则直接catch IOException
ftpClient.login(username, password); //登录到FTP服务器
//int replyCode = ftpClient.getReplyCode(); //根据replyCode可以判断登录是否成功
}catch (IOException e){
//JOptionPane.showMessageDialog(null, "FTP连接失败!", "错误提示", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
上传文件到FTP
/**
*
* @param ftpPath FTP地址
* @param filePath 本地文件地址
* @param intervalPerFile 上传间隔时间
* @param hostname 主机名
* @param port 端口号
* @param username 用户名
* @param password 密码
*/
public void uploadFile(String ftpPath, String filePath, String intervalPerFile,
String hostname, int port, String username, String password){
File localFile = new File(filePath);
File[] files = localFile.listFiles();
InputStream inputStream = null;
String fileName = "";
try{
connectFTP(hostname, port, username, password); //连接FTP服务器
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
//---------------判断获取传入的FTP文件目录是否存在--------------------
String dir = ftpPath.substring(0, ftpPath.lastIndexOf("/"));
String file = ftpPath.substring(ftpPath.lastIndexOf("/")+1);
if (!FTPExistFile(dir, file)){
int res = JOptionPane.showConfirmDialog(null, "FTP目录不存在,是否继续操作", "是否继续", JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.YES_OPTION) {
CreateDirecroty(ftpPath); //在FTP创建该文件目录
} else {
return;
}
}
//-------------------------------END---------------------------------
ftpClient.changeWorkingDirectory(ftpPath);//更改FTP当前文件目录地址
if (files != null && files.length != 0) {
for (File file1 : files) {
try {
String currentFilePath = file1.getAbsolutePath();
fileName = currentFilePath.substring(currentFilePath.lastIndexOf("\\") + 1);
inputStream = new FileInputStream(currentFilePath);
ftpClient.storeFile(fileName, inputStream);
//---------------------设置时间间隔上传------------------------------
//try {
// Thread.sleep(Integer.parseInt(intervalPerFile) * 1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
//-------------------------------END---------------------------------
} catch (Exception e) {
System.out.println(fileName + "上传失败");
e.printStackTrace();
}
}
}
ftpClient.logout();
}catch (Exception e){
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream ){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
判断FTP是否存在文件目录
public boolean FTPExistFile(String dir, String file) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(dir);
if (ftpFileArr.length > 0) {
for (FTPFile ftpFile: ftpFileArr) {
if (ftpFile.getName().equals(file)){
flag = true;
}
}
}
return flag;
}