实例——批量文件名称更改
程序员文章站
2022-04-18 17:11:14
...
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.haan</groupId>
<artifactId>filerename</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>filerename</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件重命名页</title>
</head>
<body>
<form action="rename">
文件路径:<input type="text" name="path"/><br>
截取字段:<input type="text" name="old"/><br>
新字段:<input type="text" name="new"/><br>
<input type="submit" value="批量更改"/>
</form>
</body>
</html>
控制层
package com.haan.filerename.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
public class FileController {
@RequestMapping("/rename")
public String index(@RequestParam("path") String path,
@RequestParam("old") String oldsub,
@RequestParam("new") String newsub)
{
//文件更改文件夹
File directory = new File(path);
File[] files=directory.listFiles();
for (File file:files){
String oldfilepath = file.getAbsolutePath();
String newfilepath = oldfilepath.replace(oldsub,newsub);
file.renameTo(new File(newfilepath));
System.out.println(file.getName());
}
return "success";
}
}
上一篇: 互联网零成本大众创业实操项目