8 Commits
master ... RC2

20 changed files with 2070 additions and 121 deletions

42
pom.xml
View File

@@ -5,7 +5,7 @@
<groupId>com.fjy</groupId>
<artifactId>spring</artifactId>
<version>V2.9.9</version>
<version>V3.0</version>
<packaging>jar</packaging>
<name>spring</name>
@@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RC2</version>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
@@ -54,9 +54,14 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
@@ -73,7 +78,36 @@
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
</dependencies>
<build>

View File

@@ -5,9 +5,12 @@ import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser;
import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.service.FileService;
import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.FtpOperationUtil;
import com.fjy.spring.untils.GetIPAddrUtil;
import com.fjy.spring.untils.RemoteCommandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@@ -19,6 +22,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -33,6 +37,9 @@ public class DeleteController {
@Autowired
private FileService fileService;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
@Autowired
private LogService logService;
@@ -41,54 +48,59 @@ public class DeleteController {
@GetMapping("/home/findfile")
@ResponseBody
public String findFilePath(@RequestParam(value = "fileid") Integer fileid){
public String findFilePath(@RequestParam(value = "fileid") Integer fileid) {
TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid);
TbFile resfile = fileService.findFileById(tbFile);
return resfile.getColfilepath();
return resfile.getColfilepath();
}
/**
* 删除文件,可以是文件或文件夹
*/
@RequestMapping("/home/filedelete")
@ResponseBody
public boolean delete(@RequestParam(value = "fileid") Integer fileid)throws Exception {
public boolean delete(@RequestParam(value = "fileid") Integer fileid) throws Exception {
TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid);
TbFile resfile = fileService.findFileById(tbFile);
File filepath = new File(resfile.getColfilepath());
if (!filepath.exists()) {
log.error("删除文件失败:" + resfile.getColfilename() + "不存在!");
return false;
} else {
if (filepath.isFile()){
deleteFile(resfile.getColfilepath(),resfile.getColfileid());
return true;
}
else{
deleteDirectory(resfile.getColfilepath());
return true;
}
}
return deleteFTPFile(resfile);
}
/**
* 删除单个文件
*/
public boolean deleteFile(String fileName,Integer fileid) {
public boolean deleteFile(String fileName, Integer fileid) {
File file = new File(fileName);
TbFile tbFile = new TbFile();
tbFile.setColfileid(fileid);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
try {
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
System.out.println("【fileName】" + fileName);
boolean flagExistsFile = ftpOperationUtil.isExistsFile(fileName, tbFile.getColfilename());
if (flagExistsFile) {
boolean flagDeleteFile = ftpOperationUtil.deleteFile(fileName);
System.out.println("【flagDeleteFile】" + flagDeleteFile);
}
} catch (IOException e) {
e.printStackTrace();
}
if (file.delete()) {
fileService.deleteFileById(tbFile);
log.info("删除单个文件" + fileName + "成功!");
TbUser user =(TbUser)request.getSession().getAttribute(USER_SESSION_KEY);
TbUser user = (TbUser) request.getSession().getAttribute(USER_SESSION_KEY);
//写入日志信息
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -114,11 +126,38 @@ public class DeleteController {
}
}
public boolean deleteFTPFile(TbFile tbFile) throws IOException {
tbFile.setColfileid(tbFile.getColfileid());
String path = fileService.findFileById(tbFile).getColfilepath();
//直接删除
RemoteCommandUtil.deleteFile(path, remoteExecuteProperties);
fileService.deleteFileById(tbFile);
log.info("删除单个文件" + path + "成功!");
TbUser user = (TbUser) request.getSession().getAttribute(USER_SESSION_KEY);
//写入日志信息
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateNowStr = sdf.format(date);
TbLog log = new TbLog();
log.setUserid(user.getColuserid());
log.setColtime(dateNowStr);
log.setColheader("删除单个文件" + path + "成功!");
log.setRequestURL(request.getRequestURL().toString());
//解决nginx代理后IP地址获取问题
log.setColip(GetIPAddrUtil.getIpAddr(request));
logService.addLogRec(log);
return true;
}
/**
* 删除目录及目录下的文件
*功能暂时不开放
* @param path
* 要删除的目录的文件路径
* 功能暂时不开放
*
* @param path 要删除的目录的文件路径
* @return 目录删除成功返回true否则返回false
*/
public boolean deleteDirectory(String path) {

View File

@@ -5,11 +5,15 @@ import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser;
import com.fjy.spring.enums.ResultEnum;
import com.fjy.spring.exception.UserException;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.properties.ServerProperties;
import com.fjy.spring.service.FileService;
import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.LogUtil;
import com.fjy.spring.untils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@@ -30,6 +34,7 @@ import java.util.zip.ZipOutputStream;
import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY;
@Controller
@Slf4j
public class DownLoadController {
/**
* 服务器配置信息
@@ -37,6 +42,9 @@ public class DownLoadController {
@Autowired
private ServerProperties serverProperties;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
@Autowired
private FileService fileService;
@@ -75,7 +83,7 @@ public class DownLoadController {
throw new UserException(ResultEnum.EMPTY_DATA);
}
@RequestMapping("/home/download/dodownload")
public String download(@RequestParam Integer fileId, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
@@ -84,8 +92,8 @@ public class DownLoadController {
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
TbFile file = new TbFile();
file.setColfileid(fileId);
@@ -111,7 +119,7 @@ public class DownLoadController {
bos.write(buff, 0, bytesRead);
}
//记录下载日志
addVisitLog("下载文件"+tbFile.getColrealname()+" "+tbFile.getColfilename());
addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
} catch (Exception e) {
@@ -138,6 +146,74 @@ public class DownLoadController {
}
@RequestMapping("/home/download/dodownload")
public String downloadFromFTP(@RequestParam Integer fileId, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
TbFile file = new TbFile();
file.setColfileid(fileId);
TbFile tbFile = fileService.findFileById(file);
String ctxPath = tbFile.getColfilepath();
String downLoadPath = ctxPath;
FtpOperationUtil ftpUtil = new FtpOperationUtil();
try {
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(tbFile.getColfilename().getBytes("utf-8"), "ISO8859-1"));
ftpUtil.connectServer();
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
String path = "/upload/" + tbFile.getCourseName() + "/" + tbFile.getWorkFolder() + "/";
System.out.println("【path】" + path);
InputStream inputStream = ftpUtil.downFile(path, tbFile.getColfilename());
System.out.println("【available】" + inputStream.available());
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
// 记录下载日志
addVisitLog("下载文件" + tbFile.getColrealname() + " " + tbFile.getColfilename());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
ftpUtil.closeServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/**
* 传入课程名和文件夹名称,打包下载目录下所有文件
*
@@ -145,7 +221,6 @@ public class DownLoadController {
* @param folder
* @param response
*/
@GetMapping("/home/admin/download/downloadzip")
public void batDownload(@RequestParam(value = "courseName") String courseName,
@RequestParam(value = "Folder") String folder, HttpServletResponse response) {
//获取文件夹名称
@@ -196,7 +271,7 @@ public class DownLoadController {
}
//记录下载日志
addVisitLog("下载压缩文件"+zipFile.getName());
addVisitLog("下载压缩文件" + zipFile.getName());
} catch (Exception e) {
e.printStackTrace();
@@ -217,8 +292,8 @@ public class DownLoadController {
}
}
//将打包好的文件输出到客户端
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
long fileLength = new File(desPath).length();
response.setContentType("application/x-msdownload;");
@@ -253,6 +328,49 @@ public class DownLoadController {
}
}
@GetMapping("/home/admin/download/downloadzip")
public void batFTPDownloadZip(@RequestParam(value = "courseName") String courseName,
@RequestParam(value = "Folder") String folder, HttpServletResponse response) throws IOException {
//获取文件夹名称
String paths = "/upload/" + courseName + "/" + folder;
String zipPath = "/zip/";
List<String> pathList;
pathList = getFileString(paths);
//需要压缩的文件--包括文件地址和文件名
String[] path = pathList.toArray(new String[0]);
// 要生成的压缩文件地址和文件名称
String zipFileName = courseName + folder + ".zip";
String desPath = zipPath + "/" + zipFileName;
//System.out.println("打包文件存储地址:"+desPath);
//登录FTP
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
if (!ftpOperationUtil.existDirectory(zipPath)) {
ftpOperationUtil.createDirectory(zipPath);
}
String desZipPath = remoteExecuteProperties.getPath() + "zip/";
RemoteCommandUtil.zipFile(desZipPath,zipFileName,remoteExecuteProperties,"upload/" + courseName + "/" + folder);
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(zipFileName.getBytes("utf-8"), "ISO8859-1"));
InputStream inputStream = ftpOperationUtil.downFile("/zip/",zipFileName);
System.out.println("【available】" + inputStream.available());
//将打包好的文件输出到客户端
BufferedInputStream bis = new BufferedInputStream(inputStream);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
// 记录下载日志
addVisitLog("下载文件" + desZipPath + zipFileName);
}
/**
* 获取目录下所有文件的路径
*
@@ -299,6 +417,48 @@ public class DownLoadController {
}
}*/
public void downloadConfigFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
FTPClient ftpClient = new FTPClient();
try {
int reply;
ftpClient.connect("120.120.120.156", 21);
ftpClient.login("user1", "user1");
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return;
}
ftpClient.changeWorkingDirectory("/GOS_CAS/BACKUP/cas_config_backup");//转移到FTP服务器目录
FTPFile[] fs = ftpClient.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].getName().equals(fileName)) {
String saveAsFileName = new String(fs[i].getName().getBytes("UTF-8"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName);
OutputStream os = response.getOutputStream();
ftpClient.retrieveFile(fs[i].getName(), os);
os.flush();
os.close();
break;
}
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
}
/**
* 登陆后的访问日志记录
*

View File

@@ -5,15 +5,13 @@ import com.fjy.spring.domain.Homework;
import com.fjy.spring.domain.TbFile;
import com.fjy.spring.domain.TbLog;
import com.fjy.spring.domain.TbUser;
import com.fjy.spring.properties.RemoteExecuteProperties;
import com.fjy.spring.properties.ServerProperties;
import com.fjy.spring.service.FileService;
import com.fjy.spring.service.HomeworkService;
import com.fjy.spring.service.LogService;
import com.fjy.spring.untils.FormatFileSizeUtil;
import com.fjy.spring.untils.GetIPAddrUtil;
import com.fjy.spring.untils.LogUtil;
import com.fjy.spring.untils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@@ -24,10 +22,9 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY;
@@ -42,6 +39,9 @@ public class UpLoadController {
@Autowired
private ServerProperties serverProperties;
@Autowired
private RemoteExecuteProperties remoteExecuteProperties;
/**
* 文件相关数据库操作
*/
@@ -160,7 +160,7 @@ public class UpLoadController {
TbUser user = (TbUser) request.getSession().getAttribute(GlobalConstant.USER_SESSION_KEY);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String dateNowStr = sdf.format(date);
String dateNowStr2 = sdf2.format(date);
String uploadUrl;
@@ -171,15 +171,8 @@ public class UpLoadController {
uploadUrl = serverProperties.getFilePath() + "upload/";
}
File dir = new File(uploadUrl);
if (!dir.exists()) {
dir.mkdirs();
}
List<String> fileList = new ArrayList<String>();
for (MultipartFile file : files.values()) {
Homework homework = new Homework();
//管理员上传不需要传workId
if (workId != null) {
@@ -204,33 +197,6 @@ public class UpLoadController {
tbFile.setColfilename(filename);
}
File targetFile = new File(pathname);
//若文件已存在则自动重命名
if (targetFile.exists()) {
String bakpathname;
if (rename) {
bakpathname = uploadUrl + "bak/" + user.getColstudentno() + user.getColrealname() + suffix;
} else {
bakpathname = uploadUrl + "bak/" + filename;
}
log.info("源文件路径:" + pathname);
TbFile file1 = fileService.findByFilepath(pathname);
file1.setColfilepath(bakpathname + "." + dateNowStr2 + ".bak");
file1.setColfilename(file1.getColfilename() + "." + dateNowStr2 + ".bak");
if (fileService.addFile(file1)) {
log.info("重命名文件数据库更新成功");
} else {
log.error("重命名文件数据库更新失败");
}
File mvfile = new File(bakpathname + "." + dateNowStr2 + ".bak");
try {
FileUtils.moveFile(targetFile, mvfile);
log.info("源文件:" + targetFile.getName() + "已重命名为:" + mvfile.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("文件上传到: " + uploadUrl + filename);
log.info("文件大小: " + FormatFileSizeUtil.GetFileSize(file.getSize()));
log.info("文件名: " + filename);
@@ -246,37 +212,64 @@ public class UpLoadController {
tbFile.setCourseName(courseName);
tbFile.setWorkFolder(folder);
if (fileService.addFile(tbFile)) {
log.info("记录写入数据库成功");
try {
FtpOperationUtil ftpOperationUtil = new FtpOperationUtil();
ftpOperationUtil.connectServer();
InputStream inputStream = file.getInputStream();
String path = "/upload/" + courseName + "/" + folder + "/";
boolean flagExistsFile = ftpOperationUtil.isExistsFile(path, tbFile.getColfilename());
System.out.println("flagExistsFile" + flagExistsFile);
//若文件已存在则自动重命名
if (flagExistsFile) {
String oldFileName;
if (rename) {
oldFileName = path + "bak/" + filePrefix + user.getColstudentno() + user.getColrealname() + fileSuffix + suffix;
} else {
oldFileName = path + "bak/" + filename;
}
log.info("源文件路径:" + pathname);
// 记录上传日志
addVisitLog("上传了" + tbFile.getColrealname() + "->" + tbFile.getColfilename());
} else {
log.error("记录写入数据库失败");
String newFileName = tbFile.getColfilename() + "." + dateNowStr2 + ".bak";
// 数据库查找已存在文件的记录
TbFile file1 = fileService.findByFilepath(pathname);
file1.setColfilepath(oldFileName + "." + dateNowStr2 + ".bak");
file1.setColfilename(file1.getColfilename() + "." + dateNowStr2 + ".bak");
String bakPath = path + "bak/";
System.out.println("【path】" + bakPath + "【originPath】" + pathname +
"【filename】" + tbFile.getColfilename() + "【newFileName】" + newFileName);
RemoteCommandUtil.moveFile(pathname, bakPath, newFileName, remoteExecuteProperties);
log.info("源文件:" + oldFileName + "已重命名为:" + newFileName);
if (fileService.addFile(file1)) {
log.info("重命名文件数据库更新成功");
} else {
log.error("重命名文件数据库更新失败");
}
}
boolean flag = ftpOperationUtil.uploadFile(inputStream,
tbFile.getColfilename(), path);
if (fileService.addFile(tbFile)) {
log.info("记录写入数据库成功");
// 记录上传日志
addVisitLog("上传了" + tbFile.getColrealname() + "->" + tbFile.getColfilename());
} else {
log.error("记录写入数据库失败");
}
ftpOperationUtil.closeServer();
} catch (IOException e) {
e.printStackTrace();
}
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
file.transferTo(targetFile);
fileList.add(
request.getScheme() + "://" + request.getServerName() + ":"
+ serverProperties.getPortNum() + request.getContextPath() + "/upload/"
+ file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 登陆后的访问日志记录
*
* @param content
*/
private void addVisitLog(String content) {

View File

@@ -0,0 +1,23 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-07 19:52
*/
@Data
public class FtpProperties {
//服务器地址名称
private String server = "104.223.24.81";
//端口号
private int port = 21;
//用户名称
private String username = "cms";
//密码
private String password = "imis2";
//工作目录
private String location = null;
}

View File

@@ -0,0 +1,20 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-10 12:34
*/
@Data
@ConfigurationProperties(prefix = "remoteproperties")
@Component
public class RemoteExecuteProperties {
private String ip;
private String user;
private String password;
private String path;
private int port;
}

View File

@@ -1,27 +1,13 @@
package com.fjy.spring.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "serverproperties")
@Data
public class ServerProperties {
private String portNum;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getPortNum() {
return portNum;
}
public void setPortNum(String portNum) {
this.portNum = portNum;
}
}

View File

@@ -0,0 +1,641 @@
package com.fjy.spring.untils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import com.fjy.spring.properties.FtpProperties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author F嘉阳
* @date 2018-05-07 19:56
*/
public class FtpOperationUtil {
private FTPClient ftpClient;
private static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
private static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
/**
* 利用FtpProperties进行服务器连接
*
* @throws SocketException
* @throws IOException
*/
public void connectServer() throws SocketException,
IOException {
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
public void connectServer(String path) throws SocketException,
IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(path)) {
createDirectory(path);
}
ftpClient.changeWorkingDirectory(path);
FtpProperties ftpProperties = new FtpProperties();
String server = ftpProperties.getServer();
int port = ftpProperties.getPort();
String user = ftpProperties.getUsername();
String password = ftpProperties.getPassword();
String location = ftpProperties.getLocation();
connectServer(server, port, user, password, location);
}
/**
* 使用详细信息进行服务器连接
*
* @param server服务器地址名称
* @param port端口号
* @param user用户名
* @param password用户密码
* @param path转移到FTP服务器目录
* @throws SocketException
* @throws IOException
*/
public void connectServer(String server, int port, String user,
String password, String path) throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
System.out.println("Connected to " + server + ".");
//连接成功后的回应码
System.out.println(ftpClient.getReplyCode());
ftpClient.login(user, password);
if (path != null && path.length() != 0) {
ftpClient.changeWorkingDirectory(path);
}
ftpClient.setBufferSize(1024);//设置上传缓存大小
ftpClient.setControlEncoding("UTF-8");//设置编码
ftpClient.setFileType(BINARY_FILE_TYPE);//设置文件类型
}
/**
* 设置传输文件类型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE
* 二进制文件或文本文件
*
* @param fileType
* @throws IOException
*/
public void setFileType(int fileType) throws IOException {
ftpClient.setFileType(fileType);
}
/**
* 关闭连接
*
* @throws IOException
*/
public void closeServer() throws IOException {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.logout();//退出FTP服务器
ftpClient.disconnect();//关闭FTP连接
}
}
/**
* 转移到FTP服务器工作目录
*
* @param path
* @return
* @throws IOException
*/
public boolean changeDirectory(String path) throws IOException {
return ftpClient.changeWorkingDirectory(path);
}
/**
* 在服务器上创建目录
*
* @param pathName
* @return
* @throws IOException
*/
public boolean createDirectory(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.makeDirectory(pathName);
}
/**
* 创建多级目录
*
* @param multiDirectory
* @return
*/
public boolean createMultiDirectory(String multiDirectory) {
boolean bool = false;
try {
String[] dirs = multiDirectory.split("/");
ftpClient.changeWorkingDirectory("/");
//按顺序检查目录是否存在,不存在则创建目录
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
if (ftpClient.makeDirectory(dirs[i])) {
if (!ftpClient.changeWorkingDirectory(dirs[i])) {
return false;
}
} else {
return false;
}
}
}
bool = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
return bool;
}
}
/**
* 在服务器上删除目录
*
* @param path
* @return
* @throws IOException
*/
public boolean removeDirectory(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.removeDirectory(path);
}
/**
* 删除所有文件和目录
*
* @param path
* @param isAll true:删除所有文件和目录
* @return
* @throws IOException
*/
public boolean removeDirectory(String path, boolean isAll)
throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (!isAll) {
return removeDirectory(path);
}
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr == null || ftpFileArr.length == 0) {
return removeDirectory(path);
}
//
for (FTPFile ftpFile : ftpFileArr) {
String name = ftpFile.getName();
if (ftpFile.isDirectory()) {
System.out.println("* [sD]Delete subPath [" + path + "/" + name + "]");
removeDirectory(path + "/" + name, true);
} else if (ftpFile.isFile()) {
System.out.println("* [sF]Delete file [" + path + "/" + name + "]");
deleteFile(path + "/" + name);
} else if (ftpFile.isSymbolicLink()) {
} else if (ftpFile.isUnknown()) {
}
}
return ftpClient.removeDirectory(path);
}
/**
* 检查目录在服务器上是否存在 true存在 false不存在
*
* @param dirName
* @return
* @throws IOException
*/
public boolean existDirectory(String dirName) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles("/");
for (FTPFile ftpFile : ftpFileArr) {
if (ftpFile.isDirectory()
&& ftpFile.getName().equalsIgnoreCase(dirName)) {
flag = true;
break;
}
}
return flag;
}
/**
* 判断给定路径是否存在
*
* @param path
* @return
* @throws IOException
*/
public boolean existMultiDirectory(String path) throws IOException {
boolean flag = false;
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 0; dirs != null && i < dirs.length; i++) {
FTPFile[] ftpFileArr = ftpClient.listFiles();
for (FTPFile ftpFile : ftpFileArr) {
// 判断是否为最后一级目录
if (ftpFile.isDirectory()
&& ftpFile.getName().equalsIgnoreCase(dirs[dirs.length - 1])) {
flag = true;
break;
}
}
// 进入下一级目录
ftpClient.changeWorkingDirectory(new String(dirs[i].getBytes("UTF-8"), "iso-8859-1"));
}
}
return flag;
}
public boolean isExistsFile(String fileName) {
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] file = ftpClient.listFiles(fileName);
return file.length > 0 ? true : false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 查看指定路径下是否存在该文件
*
* @param path
* @param fileName
* @return
*/
public boolean isExistsFile(String path, String fileName) throws IOException {
boolean flagChange = false;
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
flagChange = ftpClient.changeWorkingDirectory(dirs[i]);
}
}
// 该语句必须位于创建目录之后
System.out.println("【目录切换】" + path + flagChange);
try {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] file = ftpClient.listFiles(fileName);
return file.length > 0;
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
return false;
}
}
/**
* 实现文件移动操作
* @param desPath
* @param originPath
* @param oldFileName
* @param newFileName
* @return
* @throws IOException
*/
public boolean moveFile(String desPath, String originPath, String oldFileName,String newFileName) throws IOException {
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
ftpClient.enterLocalPassiveMode();
boolean moveFlag;
// 目标文件目录是否存在
System.out.println("【desPath】"+desPath);
if (!existMultiDirectory(desPath)) {
System.out.println("【创建目录】"+createMultiDirectory(desPath));
}
// 切换到源文件目录
changWorkingDir(originPath);
//转换成输入流
InputStream is = null;
is = ftpClient.retrieveFileStream(oldFileName);
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
System.out.println("【inputStream】"+is.available()+" "+bufferedInputStream.available());
is.close();
boolean cpcflag = ftpClient.completePendingCommand();
System.out.println("【completePendingCommand】"+cpcflag);
// 切换到目标文件目录
changWorkingDir(desPath);
//复制文件
moveFlag = ftpClient.storeFile(newFileName, bufferedInputStream);
System.out.println("【创建目录】"+moveFlag);
if (moveFlag) {
changWorkingDir(originPath);
//删除源文件
ftpClient.deleteFile(oldFileName);
bufferedInputStream.close();
}
return moveFlag;
}
/**
* 得到文件列表,listFiles返回包含目录和文件它返回的是一个FTPFile数组
* listNames():只包含目录的字符串数组
* String[] fileNameArr = ftpClient.listNames(path);
*
* @param path:服务器上的文件目录:/DF4
*/
public List<String> getFileList(String path) throws IOException {
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
FTPFile[] ftpFiles = ftpClient.listFiles(path);
//通过FTPFileFilter遍历只获得文件
/* FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
@Override
public boolean accept(FTPFile ftpFile) {
return ftpFile.isFile();
}
}); */
List<String> retList = new ArrayList<String>();
if (ftpFiles == null || ftpFiles.length == 0) {
return retList;
}
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.isFile()) {
retList.add(ftpFile.getName());
}
}
return retList;
}
/**
* 获取所有文件和目录
*
* @return
* @throws IOException
*/
public String[] list() throws IOException {
return ftpClient.listNames();
}
public String[] list(String path) throws IOException {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
ftpClient.enterLocalPassiveMode();
for (int i = 1; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
ftpClient.changeWorkingDirectory(dirs[i]);
}
return ftpClient.listNames();
}
/**
* 删除服务器上的文件
*
* @param pathName
* @return
* @throws IOException
*/
public boolean deleteFile(String pathName) throws IOException {
pathName = new String(pathName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.deleteFile(pathName);
}
public boolean renameFile(String oldFileName, String newFileName) throws IOException {
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.rename(oldFileName, newFileName);
}
/**
* 上传文件到ftp服务器
* 在进行上传和下载文件的时候,设置文件的类型最好是:
* ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE)
* localFilePath:本地文件路径和名称
* remoteFileName:服务器文件名称
*/
public boolean uploadFile(String localFilePath, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
if (!existDirectory(localFilePath)) {
createDirectory(localFilePath);
ftpClient.changeWorkingDirectory(localFilePath);
}
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(localFilePath);
//我们可以使用BufferedInputStream进行封装
//BufferedInputStream bis=new BufferedInputStream(iStream);
//flag = ftpClient.storeFile(remoteFileName, bis);
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
public boolean uploadFile(String localFilePath, String path, String remoteFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(localFilePath);
if (path != null && path.length() != 0) {
createDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(remoteFileName, iStream);
} catch (IOException e) {
System.out.println(e.getMessage());
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 上传文件到ftp服务器上传新的文件名称和原名称一样
*
* @param fileName文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(String fileName) throws IOException {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
return uploadFile(fileName, fileName);
}
/**
* 上传文件到ftp服务器
*
* @param iStream 输入流
* @param newName 新文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String newName)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 上传文件到ftp服务器
*
* @param iStream 输入流
* @param newName 新文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String newName, String path)
throws IOException {
newName = new String(newName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
try {
if (path != null && path.length() != 0) {
createMultiDirectory(path);
// 该语句必须位于创建目录之后
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + flagChange);
}
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
System.out.println(e.getMessage());
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
/**
* 从ftp服务器上下载文件到本地
*
* @param remoteFileNameftp服务器上文件名称
* @param localFileName本地文件名称
* @return
* @throws IOException
*/
public boolean download(String remoteFileName, String localFileName)
throws IOException {
remoteFileName = new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1");
boolean flag = false;
File outfile = new File(localFileName);
OutputStream oStream = null;
try {
oStream = new FileOutputStream(outfile);
//我们可以使用BufferedOutputStream进行封装
//BufferedOutputStream bos=new BufferedOutputStream(oStream);
//flag = ftpClient.retrieveFile(remoteFileName, bos);
flag = ftpClient.retrieveFile(remoteFileName, oStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
oStream.close();
}
return flag;
}
/**
* 从ftp服务器上下载文件到本地
*
* @param sourceFileName服务器资源文件名称
* @return InputStream 输入流
* @throws IOException
*/
public InputStream downFile(String sourceFileName) throws IOException {
sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1");
return ftpClient.retrieveFileStream(sourceFileName);
}
public InputStream downFile(String path, String sourceFileName) throws IOException {
sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1");
path = new String(path.getBytes("UTF-8"), "iso-8859-1");
if (path != null && path.length() != 0) {
boolean flagChange = ftpClient.changeWorkingDirectory(path);
System.out.println("【目录切换】" + path + flagChange);
}
return ftpClient.retrieveFileStream(sourceFileName);
}
/**
* 采用递归方式切换目录
*
* @param path
* @throws IOException
*/
public void changWorkingDir(String path) throws IOException {
if (path != null && path.length() != 0) {
String[] dirs = path.split("/");
ftpClient.changeWorkingDirectory("/");
for (int i = 0; dirs != null && i < dirs.length; i++) {
dirs[i] = new String(dirs[i].getBytes("UTF-8"), "iso-8859-1");
ftpClient.changeWorkingDirectory(dirs[i]);
System.out.println("【当前目录】" + new String(ftpClient.printWorkingDirectory().getBytes("iso-8859-1"), "UTF-8"));
}
}
}
}

View File

@@ -0,0 +1,430 @@
package com.fjy.spring.untils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author F嘉阳
* @date 2018-05-06 11:35
*/
public class FtpUtils {
// private static final String FTP_URL = "176.122.138.235";
private static final String FTP_URL = "192.168.79.138";
private static final int PORT = 21;
private static final String USER_NAME = "cms";
private static final String PASSWORD = "imis2";
/**
* 本地字符编码
*/
private static final String LOCAL_CHARSET = "UTF-8";
/**
* FTP协议里面规定文件名编码为iso-8859-1
*/
private static String SERVER_CHARSET = "iso-8859-1";
/**
* ftp上传单个文件
*
* @param directory 上传至ftp的路径名不包括ftp地址
* @param srcFileName 要上传的文件全路径名
* @param destName 上传至ftp后存储的文件名
* @throws IOException
*/
public static boolean upload(String directory, String srcFileName, String destName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
destName = new String(destName.getBytes("UTF-8"), "iso-8859-1");
FTPClient ftpClient = makeConnectionFactory();
FileInputStream fis = null;
boolean result = false;
try {
File srcFile = new File(srcFileName);
fis = new FileInputStream(srcFile);
// 设置上传目录
ftpClient.changeWorkingDirectory(directory);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding(LOCAL_CHARSET);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
result = ftpClient.storeFile(destName, fis);
return result;
} catch (NumberFormatException e) {
System.out.println("FTP端口配置错误:不是数字:");
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* FTP单个文件下载
*
* @param directory 要下载的文件所在ftp的路径名不包含ftp地址
* @param destFileName 要下载的文件名
* @param downloadName 下载后存储的文件名全路径
*/
public static boolean download(String directory, String destFileName, String downloadName) throws IOException {
FTPClient ftpClient = makeConnectionFactory();
boolean result = false;
try {
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.changeWorkingDirectory(directory);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
System.out.println("destFileName:" + destFileName + ",downloadName:" + downloadName);
FileOutputStream fileOutputStream = new FileOutputStream(downloadName);
result = ftpClient.retrieveFile(destFileName, fileOutputStream);
fileOutputStream.flush();
return result;
} catch (NumberFormatException e) {
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param remotePath
* @param fileName
* @param localPath
* @return
* @author xh 测试成功 可以下载中文文件 ftp默认的编码为gbk
*/
public static boolean downFtpFile(String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(FTP_URL, PORT);
// 如果采用默认端口可以使用ftp.connect(url)的方式直接连接FTP服务器
// 登录
ftp.login(USER_NAME, PASSWORD);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
String fname = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");
if (fname.equals(fileName)) {
File localFile = new File(localPath + fname);
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
break;
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* @param fileName
* @return
* @author xh 测试成功 可以下载中文文件 ftp默认的编码为gbk
*/
public static OutputStream downFtpFileByStream(String fileName) {
String remotePath = "/www/ftp/cms/";
boolean success = false;
OutputStream is = null;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(FTP_URL, PORT);
// 如果采用默认端口可以使用ftp.connect(url)的方式直接连接FTP服务器
// 登录
ftp.login(USER_NAME, PASSWORD);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return null;
}
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
String fname = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");
if (fname.equals(fileName)) {
File localFile = new File(fname);
is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
return is;
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert is != null;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return null;
}
/**
* @param directory 要重命名的文件所在ftp的路径名不包含ftp地址
* @param oldFileName 要重命名的文件名
* @param newFileName 重命名后的文件名
* @throws IOException
*/
public static boolean rename(String directory, String oldFileName, String newFileName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
oldFileName = new String(oldFileName.getBytes("UTF-8"), "iso-8859-1");
newFileName = new String(newFileName.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否重命名成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
//重命名远程文件
result = ftpClient.rename(oldFileName, newFileName);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要删除的文件所在ftp的路径名不包含ftp地址
* @param fileName 要删除的文件名
* @return
* @throws IOException
*/
public static boolean remove(String directory, String fileName) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
//删除远程文件
result = ftpClient.deleteFile(fileName);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要创建的目录所在ftp的路径名不包含ftp地址
* @param newDirectory 要创建的新目录名
* @return
* @throws IOException
*/
public static boolean makeDirecotory(String directory, String newDirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
newDirectory = new String(newDirectory.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.makeDirectory(newDirectory);//创建新目录
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要重命名的目录所在ftp的路径名不包含ftp地址
* @param oldDirectory 要重命名的旧目录名
* @param newDirectory 重命名后的新目录
* @return
* @throws IOException
*/
public static boolean renameDirecotory(String directory, String oldDirectory, String newDirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
oldDirectory = new String(oldDirectory.getBytes("UTF-8"), "iso-8859-1");
newDirectory = new String(newDirectory.getBytes("UTF-8"), "iso-8859-1");
// 判断远程文件是否移除成功如果成功返回true否则返回false
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
// 重命名目录
result = ftpClient.rename(oldDirectory, newDirectory);
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory 要重命名的目录所在ftp的路径名不包含ftp地址
* @param deldirectory 要删除的目录名
* @return
* @throws IOException
*/
public static boolean removeDirecotory(String directory, String deldirectory) throws IOException {
directory = new String(directory.getBytes("UTF-8"), "iso-8859-1");
deldirectory = new String(deldirectory.getBytes("UTF-8"), "iso-8859-1");
/**
* 判断远程文件是否移除成功如果成功返回true否则返回false
*/
boolean result = false;
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
result = ftpClient.removeDirectory(deldirectory);//删除目录
return result;
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* @param directory
* @return
* @throws IOException
*/
public static String[] list(String directory) throws IOException {
FTPClient ftpClient = makeConnectionFactory();
try {
ftpClient.changeWorkingDirectory(directory);
ftpClient.enterLocalPassiveMode();
//删除目录
return ftpClient.listNames();
} catch (NumberFormatException e) {
throw e;
} catch (IOException e) {
throw new IOException("连接ftp服务器失败", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常", e);
}
}
}
/**
* 创建FTP连接的工厂方法
*
* @return
* @throws IOException
*/
private static FTPClient makeConnectionFactory() throws IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(FTP_URL, PORT);
ftpClient.login(USER_NAME, PASSWORD);
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding(LOCAL_CHARSET);
return ftpClient;
}
}

View File

@@ -0,0 +1,92 @@
package com.fjy.spring.untils;
import com.fjy.spring.properties.RemoteExecuteProperties;
import lombok.extern.slf4j.Slf4j;
/**
* 封装Linux远程命令
*
* @author F嘉阳
* @date 2018-05-13 09:11
*/
@Slf4j
public class RemoteCommandUtil {
private static RemoteExecuteCommandUtil REC;
private static String cmd;
/**
* 生成压缩文件
*
* @param desZipPath 压缩文件目标地址
* @param zipFileName 压缩文件名
* @param remoteExecuteProperties 远程参数配置类
* @param originPath 目标文件、文件夹地址
*/
public static void zipFile(String desZipPath,
String zipFileName,
RemoteExecuteProperties remoteExecuteProperties,
String originPath) {
login(remoteExecuteProperties);
desZipPath = remoteExecuteProperties.getPath() + desZipPath;
originPath = remoteExecuteProperties.getPath() + originPath;
cmd = "zip -r " + desZipPath + zipFileName + " " + originPath;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
log.error("【cmd创建压缩文件失败】" + cmd);
}
/**
* 移动文件
*
* @param originPath 源文件路径
* @param desPath 目标路径
* @param remoteExecuteProperties 远程参数配置类
* @return
*/
public static void moveFile(String originPath, String desPath, String newName, RemoteExecuteProperties remoteExecuteProperties) {
login(remoteExecuteProperties);
// 创建目标目录
mkdir(desPath, remoteExecuteProperties);
desPath = remoteExecuteProperties.getPath() + desPath;
originPath = remoteExecuteProperties.getPath() + originPath;
cmd = "mv " + originPath + " " + desPath + newName;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
/**
* 创建多级目录
*
* @param path
* @param remoteExecuteProperties
*/
public static void mkdir(String path, RemoteExecuteProperties remoteExecuteProperties) {
login(remoteExecuteProperties);
path = remoteExecuteProperties.getPath() + path;
cmd = "mkdir -p " + path;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
public static void deleteFile(String path, RemoteExecuteProperties remoteExecuteProperties){
login(remoteExecuteProperties);
path = remoteExecuteProperties.getPath() + path;
cmd = "rm -f " + path;
log.info("【cmd】" + cmd);
log.info("【res】" + REC.execute(cmd));
}
private static void login(RemoteExecuteProperties remoteExecuteProperties) {
//远程登录SSH
REC = new RemoteExecuteCommandUtil(
remoteExecuteProperties.getIp(),
remoteExecuteProperties.getUser(),
remoteExecuteProperties.getPassword(),
remoteExecuteProperties.getPort());
REC.login();
}
}

View File

@@ -0,0 +1,163 @@
package com.fjy.spring.untils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.StringUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
* @author F嘉阳
* @date 2018-05-10 12:16
*/
public class RemoteExecuteCommandUtil {
//字符编码默认是utf-8
private static String DEFAULTCHART="UTF-8";
private Connection conn;
private String ip;
private String userName;
private String userPwd;
private int port;
public RemoteExecuteCommandUtil(String ip, String userName, String userPwd,int port) {
this.ip = ip;
this.userName = userName;
this.userPwd = userPwd;
this.port = port;
}
public RemoteExecuteCommandUtil() {
}
/**
* 远程登录linux的主机
* @author Ickes
* @since V0.1
* @return
* 登录成功返回true否则返回false
*/
public Boolean login(){
boolean flg=false;
try {
conn = new Connection(ip,port);
conn.connect();//连接
flg=conn.authenticateWithPassword(userName, userPwd);//认证
} catch (IOException e) {
e.printStackTrace();
}
return flg;
}
/**
* @author Ickes
* 远程执行shll脚本或者命令
* @param cmd
* 即将执行的命令
* @return
* 命令执行完后返回的结果值
* @since V0.1
*/
public String execute(String cmd){
String result="";
try {
if(login()){
Session session= conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result=processStdout(session.getStdout(),DEFAULTCHART);
//如果为得到标准输出为空,说明脚本执行出错了
if(StringUtils.isBlank(result)){
result=processStdout(session.getStderr(),DEFAULTCHART);
}
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @author Ickes
* 远程执行shll脚本或者命令
* @param cmd
* 即将执行的命令
* @return
* 命令执行成功后返回的结果值如果命令执行失败返回空字符串不是null
* @since V0.1
*/
public String executeSuccess(String cmd){
String result="";
try {
if(login()){
Session session= conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result=processStdout(session.getStdout(),DEFAULTCHART);
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 解析脚本执行返回的结果集
* @author Ickes
* @param in 输入流对象
* @param charset 编码
* @since V0.1
* @return
* 以纯文本的格式返回
*/
private String processStdout(InputStream in, String charset){
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
String line=null;
while((line=br.readLine()) != null){
buffer.append(line+"\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void setCharset(String charset) {
DEFAULTCHART = charset;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}

View File

@@ -7,7 +7,13 @@ server:
port: 8080
serverproperties:
port_num: 8080
filePath: F:\JAVA Workspace\Temp\
filePath: /
remoteproperties:
ip: 104.223.24.81
port: 26460
user: root
password: 27894869root
path: /www/wwwroot/cmsftp
spring:
thymeleaf:
prefix: classpath:/templates/

View File

@@ -13,6 +13,12 @@ server:
serverproperties:
port_num: 8085
filePath: /www/cmsfile/
ftp:
server: 176.122.138.235
port: 21
username: cms
password: imis2
location: /www/ftp/cms/
spring:
thymeleaf:
prefix: classpath:/templates/

View File

@@ -1,4 +1,4 @@
#控制配置文件调用
spring:
profiles:
active: prod
active: dev

View File

@@ -25,8 +25,8 @@
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<!--<fileNamePattern>F:\JAVA Workspace\Temp\log\%d\info.%d.log</fileNamePattern>-->
<fileNamePattern>/www/cmsfile/%d/info.%d.log</fileNamePattern>
<fileNamePattern>F:\JAVA Workspace\Temp\log\%d\info.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/info.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender>
@@ -44,8 +44,8 @@
<!--滚动策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径文件名,文件名包含时间-->
<!--<fileNamePattern>F:\JAVA Workspace\Temp\log\error.%d.log</fileNamePattern>-->
<fileNamePattern>/www/cmsfile/%d/error.%d.log</fileNamePattern>
<fileNamePattern>F:\JAVA Workspace\Temp\log\error.%d.log</fileNamePattern>
<!--<fileNamePattern>/www/cmsfile/%d/error.%d.log</fileNamePattern>-->
</rollingPolicy>
</appender>

View File

@@ -0,0 +1,162 @@
package com.fjy.spring.untils;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
public class FtpOperationUtilTest {
private static final String FILE_NAME = "ERP实验1销售预测与SOP.doc";
private static final String DESTINATION = "F:\\JAVA Workspace\\Temp\\upload\\ERP实验1销售预测与SOP.doc";
private static final String LOCAL_DESTINATION = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
private static FtpOperationUtil makeConnectionFactory() {
FtpOperationUtil ftpUtil = new FtpOperationUtil();
try {
ftpUtil.connectServer();
} catch (IOException e) {
e.printStackTrace();
}
return ftpUtil;
}
private static void listFiles(FtpOperationUtil ftpUtil) throws IOException {
List<String> list = ftpUtil.getFileList("/");
for (String str : list) {
System.out.println(str);
}
}
@Test
public void createDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.createDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void removeDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void removeDirectory1() throws IOException {
createDirectory();
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.removeDirectory("创建目录", true);
listFiles(ftpUtil);
}
@Test
public void existDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory1:" + flag);
ftpUtil.createDirectory("创建目录");
flag = ftpUtil.existDirectory("创建目录");
System.out.println("existDirectory2:" + flag);
ftpUtil.removeDirectory("创建目录");
listFiles(ftpUtil);
}
@Test
public void changWorkingDir() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.changWorkingDir("/upload/信息安全/时间测试/");
String[] lists = ftpUtil.list();
for (String list : lists) {
System.out.println(list);
}
ftpUtil.changWorkingDir("/");
String[] lists2 = ftpUtil.list();
for (String list : lists2) {
System.out.println(list);
}
}
@Test
public void existMultiDirectory() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.existMultiDirectory("/upload/信息安全/时间测试/");
System.out.println("existMultiDirectory:" + flag);
}
@Test
public void isExistsFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
boolean flag = ftpUtil.isExistsFile("/信息安全/","15级15251101261FJY实验二.doc.2018_05_09_21_25_47.bak");
System.out.println("isExistsFile:" + flag);
listFiles(ftpUtil);
}
@Test
public void getFileList() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.getFileList("/");
}
@Test
public void list() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
String[] lists = ftpUtil.list("/upload/");
for (String list : lists) {
System.out.println(list);
}
}
@Test
public void deleteFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.deleteFile(FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile2() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
File file = new File(DESTINATION);
InputStream in = new FileInputStream(file);
ftpUtil.uploadFile(in, FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void uploadFile3() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.uploadFile(DESTINATION,"/信息安全/", FILE_NAME);
listFiles(ftpUtil);
}
@Test
public void download() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
ftpUtil.download(FILE_NAME, DESTINATION);
listFiles(ftpUtil);
}
@Test
public void moveFile() throws IOException {
FtpOperationUtil ftpUtil = makeConnectionFactory();
String desPath = "/upload/bak/";
String originPath = "/upload/";
ftpUtil.moveFile(desPath,originPath,FILE_NAME,FILE_NAME);
listFiles(ftpUtil);
}
}

View File

@@ -0,0 +1,83 @@
package com.fjy.spring.untils;
import org.junit.Test;
import static org.junit.Assert.*;
public class FtpUtilsTest {
private static final String destName = "ERP实验1销售预测与SOP.doc";
private static final String directory = "/www/ftp/cms/";
@Test
public void upload() throws Exception{
String srcFileName = "F:\\JAVA Workspace\\Temp\\upload\\ERP实验1销售预测与SOP.doc";
FtpUtils.upload(directory,srcFileName,destName);
list();
}
/**
* WIN10下载文件为0kb请勿使用
* @throws Exception
*/
@Test
public void download() throws Exception{
String downloadName = "F:\\JAVA Workspace\\Temp\\ERP实验1销售预测与SOP.doc";
FtpUtils.download(directory,destName,downloadName);
}
@Test
public void downFtpFile() throws Exception{
String downloadName = "F:\\JAVA Workspace\\Temp\\";
boolean res = FtpUtils.downFtpFile(directory,destName,downloadName);
System.out.println(res);
}
@Test
public void rename() throws Exception{
String oldFileName = destName;
String newFileName = "新名称.doc";
FtpUtils.rename(directory,oldFileName, newFileName);
list();
}
@Test
public void remove() throws Exception{
FtpUtils.remove(directory,"新名称.doc");
list();
}
@Test
public void makeDirecotory() throws Exception{
String newDirectory = "test";
String newDirectoryZH = "新目录";
FtpUtils.makeDirecotory(directory,newDirectory);
FtpUtils.makeDirecotory(directory,newDirectoryZH);
list();
}
@Test
public void renameDirecotory() throws Exception{
String oldDirectoryZH = "新目录";
String newDirectoryZH = "重命名目录";
FtpUtils.renameDirecotory(directory,oldDirectoryZH,newDirectoryZH);
list();
}
@Test
public void removeDirecotory() throws Exception{
String newDirectory = "test";
String newDirectoryZH = "重命名目录";
FtpUtils.removeDirecotory(directory,newDirectory);
FtpUtils.removeDirecotory(directory,newDirectoryZH);
list();
}
@Test
public void list() throws Exception{
String[] lists = FtpUtils.list(directory);
for (String list : lists){
System.out.println(list);
}
}
}

View File

@@ -0,0 +1,44 @@
package com.fjy.spring.untils;
import com.fjy.spring.properties.RemoteExecuteProperties;
import org.junit.Test;
import static org.junit.Assert.*;
public class RemoteCommandUtilTest {
private RemoteExecuteProperties rep = new RemoteExecuteProperties();
private boolean flag;
@Test
public void zipFile() {
dataSet();
String desZipPath = "/test/";
String zipFileName = "test.zip";
String originPath = "/upload/";
RemoteCommandUtil.zipFile(desZipPath, zipFileName, rep, originPath);
}
@Test
public void moveFile() {
dataSet();
String desPath = "/test/zip/";
String newName = "test.zip";
String originPath = "/test/test.zip";
RemoteCommandUtil.moveFile(originPath,desPath,newName,rep);
}
@Test
public void mkdir() {
dataSet();
String path = "/test/zip/";
RemoteCommandUtil.mkdir(path,rep);
}
private void dataSet() {
rep.setIp("104.223.24.81");
rep.setPassword("27894869root");
rep.setUser("root");
rep.setPath("/www/wwwroot/cmsftp");
rep.setPort(26460);
}
}

View File

@@ -0,0 +1,67 @@
package com.fjy.spring.untils;
import org.junit.Test;
import static org.junit.Assert.*;
public class RemoteExecuteCommandUtilTest {
RemoteExecuteCommandUtil rec=new RemoteExecuteCommandUtil("104.223.24.81", "root","27894869root",26460);
@Test
public void login() {
rec.login();
System.out.println(rec.execute("cd /1/2/3/4"));
}
@Test
public void execute() {
}
@Test
public void executeZip() {
rec.login();
System.out.println(rec.execute("zip -r /home/ftp/cms/upload/信息安全时间测试.zip /home/ftp/cms/upload/信息安全"));
}
@Test
public void executeSuccess() {
}
@Test
public void setCharset() {
}
@Test
public void getConn() {
}
@Test
public void setConn() {
}
@Test
public void getIp() {
}
@Test
public void setIp() {
}
@Test
public void getUserName() {
}
@Test
public void setUserName() {
}
@Test
public void getUserPwd() {
}
@Test
public void setUserPwd() {
}
}