1、pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--接口测试组件swagger-ui3-->
<!--基础组件-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--界面组件-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、核心代码说明
2.1、文件查询:指定目录下文件列表
/*** 文件查询:指定Linux服务器目录下文件列表 **/
public static List getFilesByDir(String dirName) throws Exception {
List list = new ArrayList<>();
File dir = new File(dirName);
File[] files = dir.listFiles();
for (File file : files) {
String type = file.isDirectory() ? "文件夹" : "文件";
String name = file.getName();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified()));
long size = file.length();
// 查询linux服务器的文件权限方法,windows会报错
Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(Paths.get(file.getCanonicalPath()));
List<String> permissons = posixFilePermissions.parallelStream().map(e -> e.name()).collect(Collectors.toList());
String privilege = new StringBuffer()
.append(permissons.contains("OWNER_READ") ? "r" : "-")
.append(permissons.contains("OWNER_WRITE") ? "w" : "-")
.append(permissons.contains("OWNER_EXECUTE") ? "x" : "-")
.append(permissons.contains("GROUP_READ") ? "r" : "-")
.append(permissons.contains("GROUP_WRITE") ? "w" : "-")
.append(permissons.contains("GROUP_EXECUTE") ? "x" : "-")
.append(permissons.contains("OTHERS_READ") ? "r" : "-")
.append(permissons.contains("OTHERS_WRITE") ? "w" : "-")
.append(permissons.contains("OTHERS_EXECUTE") ? "x" : "-")
.toString();
String result = type + ",名字为:" + name + ",时间为:" + time + ",大小为:" + size + ",权限为:" + privilege;
System.out.println(result);
list.add(result);
}
return list;
}
2.2、文件及文件夹创建
/*** 文件创建 **/
public static void createFile(String fileName) throws Exception {
new File(fileName).createNewFile();
}
/*** 文件夹创建 **/
public static void createDir(String dirName) throws Exception {
new File(dirName).mkdirs();
}
2.3、文件或文件夹重命名、删除
/*** 文件或文件夹重命名 **/
public static void renameFile(String oldPath, String newPath) throws Exception {
new File(oldPath).renameTo(new File(newPath));
}
/*** 文件或文件夹删除 **/
public static void deleteFile(String fileName) throws Exception {
new File(fileName).deleteOnExit();
}
2.4、文件内容读取
/*** 读取文件内容 ***/
public static String readFile(String fileName) throws Exception {
List<String> strings = Files.readAllLines(Paths.get(new File(fileName).getCanonicalPath()));
return String.join("\n", strings);
}
2.5、文件上传
/*** 文件上传 ***/
public static void uploadFile(MultipartFile file, String serverFilePath) throws Exception {
File dest = new File(serverFilePath);
file.transferTo(dest);
}
2.6、文件下载
/*** 文件下载 ***/
public static void downloadFile(File file, HttpServletResponse response) throws Exception {
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
if (file.exists()) {
//设置响应
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setCharacterEncoding("UTF-8");
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
while (bis.read(buffer) != -1) {
os.write(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、整体代码
3.1、文件操作代码
package com.hzp.webtest.RemoteFIleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* Linux服务器本地文件管理:
* 1、文件查询,查询对应目录下所有文件内容:
* 文件名、文件类型(目录/文件)、修改日期、文件大小、文件权限
* 2、文件操作,
* 2.1、新建文件夹/文件
* 2.2、文件重命名
* 2.3、批量删除
* 2.4、文件内容查看
* 2.5、批量上传
* 2.6、下载
*/
@RestController
@Slf4j
public class TestLocal {
/*** 文件查询:指定Linux服务器目录下文件列表 **/
public static List getFilesByDir(String dirName) throws Exception {
List list = new ArrayList<>();
File dir = new File(dirName);
File[] files = dir.listFiles();
for (File file : files) {
String type = file.isDirectory() ? "文件夹" : "文件";
String name = file.getName();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified()));
long size = file.length();
// 查询linux服务器的文件权限方法,windows会报错
Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(Paths.get(file.getCanonicalPath()));
List<String> permissons = posixFilePermissions.parallelStream().map(e -> e.name()).collect(Collectors.toList());
String privilege = new StringBuffer()
.append(permissons.contains("OWNER_READ") ? "r" : "-")
.append(permissons.contains("OWNER_WRITE") ? "w" : "-")
.append(permissons.contains("OWNER_EXECUTE") ? "x" : "-")
.append(permissons.contains("GROUP_READ") ? "r" : "-")
.append(permissons.contains("GROUP_WRITE") ? "w" : "-")
.append(permissons.contains("GROUP_EXECUTE") ? "x" : "-")
.append(permissons.contains("OTHERS_READ") ? "r" : "-")
.append(permissons.contains("OTHERS_WRITE") ? "w" : "-")
.append(permissons.contains("OTHERS_EXECUTE") ? "x" : "-")
.toString();
String result = type + ",名字为:" + name + ",时间为:" + time + ",大小为:" + size + ",权限为:" + privilege;
System.out.println(result);
list.add(result);
}
return list;
}
/*** 文件创建 **/
public static void createFile(String fileName) throws Exception {
new File(fileName).createNewFile();
}
/*** 文件夹创建 **/
public static void createDir(String dirName) throws Exception {
new File(dirName).mkdirs();
}
/*** 文件或文件夹重命名 **/
public static void renameFile(String oldPath, String newPath) throws Exception {
new File(oldPath).renameTo(new File(newPath));
}
/*** 文件或文件夹删除 **/
public static void deleteFile(String fileName) throws Exception {
new File(fileName).deleteOnExit();
}
/*** 读取文件内容 ***/
public static String readFile(String fileName) throws Exception {
List<String> strings = Files.readAllLines(Paths.get(new File(fileName).getCanonicalPath()));
return String.join("\n", strings);
}
/*** 文件上传 ***/
public static void uploadFile(MultipartFile file, String serverFilePath) throws Exception {
File dest = new File(serverFilePath);
file.transferTo(dest);
}
/*** 文件下载 ***/
public static void downloadFile(File file, HttpServletResponse response) throws Exception {
byte[] buffer = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
if (file.exists()) {
//设置响应
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setCharacterEncoding("UTF-8");
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
while (bis.read(buffer) != -1) {
os.write(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@GetMapping("/localLinuxFile")
public Object test(String methodName) {
try {
Method method = TestLocal.class.getMethod(methodName);
return method.invoke(new TestLocal());
} catch (Exception e) {
e.printStackTrace();
return "出错";
}
}
@GetMapping("/getFiles")
public Object getFiles(String dirName) {
try {
return getFilesByDir(dirName);
} catch (Exception e) {
e.printStackTrace();
return "出错";
}
}
@PostMapping("/uploadFile")
public Object uploadFile(@RequestPart MultipartFile file) {
try {
uploadFile(file, "C:\\Users\\Administrator\\Desktop\\" + UUID.randomUUID().toString() + "_" + file.getOriginalFilename());
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "出错";
}
}
@PostMapping("/downloadFile")
public Object downloadFile(String fileName, HttpServletResponse httpServletResponse) {
try {
downloadFile(new File(fileName), httpServletResponse);
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
public static void main(String[] args) throws Exception {
// createFile("C:\\Users\\Administrator\\Desktop\\m.txt");
// createDir("C:\\Users\\Administrator\\Desktop\\test\\");
// renameFile("C:\\Users\\Administrator\\Desktop\\m.txt", "C:\\Users\\Administrator\\Desktop\\n.txt");
// renameFile("C:\\Users\\Administrator\\Desktop\\test", "C:\\Users\\Administrator\\Desktop\\testA");
// deleteFile("C:\\Users\\Administrator\\Desktop\\n.txt");
// deleteFile("C:\\Users\\Administrator\\Desktop\\testA");
System.out.println(readFile("C:\\Users\\Administrator\\Desktop\\a.txt"));
}
}
3.2、swagger接口配置代码
package com.hzp.webtest.RemoteFIleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import static java.util.Collections.singletonList;
@EnableOpenApi
@Configuration
public class SpringFoxSwaggerConfig {
/**
* 配置基本信息
*/
@Bean
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger Test App Restful API")
.description("swagger test app restful api")
.version("1.0")
.build();
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build();
}
}