Java递归生成本地文件目录(树行结构)
1.读取txt文件保存的文件目录结构
2.递归生成本地文件目录树形结构,并修改目录文件前缀进行递增
3.结果截图
4.代码
package com.zfi.server.device;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@RestController
@RequestMapping("test")
@Api(tags = "test")
public class FileAddTest {
public static void main(String[] args) {
String txtFileName = "F://temp//questions.txt";
String outputDirectory = "F://temp//output";
int directoryCount = 1;
int fileCount = 1;
String currentDirectory = null; // 记录最近一次生成的目录名称
try (BufferedReader reader = new BufferedReader(new FileReader(txtFileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("-")) {
// 如果是目录行,则创建目录
String directoryName = String.format("%02d%s", directoryCount, line.substring(1).trim()); // 去掉前导的"-"
createDirectory(outputDirectory, directoryName);
currentDirectory = directoryName; // 更新最近一次生成的目录名称
directoryCount++;
} else {
// 否则,认为是文件,将其写入当前目录
if (currentDirectory != null) {
String fileName = String.format("%02d%s", fileCount, line.trim()+".md");
createFile(outputDirectory + File.separator + currentDirectory, fileName);
fileCount++;
} else {
System.out.println("警告:文件 '" + line + "' 没有对应的目录。");
}
}
}
System.out.println("文件和目录生成完成。");
} catch (IOException e) {
System.out.println("发生异常:" + e.getMessage());
e.printStackTrace();
}
}
private static void createDirectory(String parentDir, String dirName) {
File directory = new File(parentDir, dirName);
if (!directory.exists()) {
directory.mkdir();
System.out.println("生成目录:" + directory.getAbsolutePath());
} else {
System.out.println("目录已存在:" + directory.getAbsolutePath());
}
}
private static void createFile(String parentDir, String fileName) throws IOException {
File file = new File(parentDir, fileName);
if (!file.exists()) {
file.createNewFile();
System.out.println("生成文件:" + file.getAbsolutePath());
} else {
System.out.println("文件已存在:" + file.getAbsolutePath());
}
}
}