java 扫描指定路径下所有文件,将文件路径、大小以JSON格式写入指定路径下的txt文件中
时间: 2024-05-04 14:16:38 浏览: 129
好的,你可以使用Java语言编写代码来实现。以下是示例代码:
```
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class ScanFilesToJson {
public static void main(String[] args) {
String dirPath = "指定路径"; // 指定要扫描的文件夹路径
String filePath = "指定路径"; // 指定要写入的txt文件路径
List<Map<String, String>> fileList = scanFiles(dirPath); // 扫描文件并生成JSON格式数据
String jsonData = listToJson(fileList); // 将数据转换为JSON格式字符串
writeToFile(filePath, jsonData); // 将JSON格式字符串写入文件
}
/**
* 扫描指定路径下的所有文件,生成文件路径和大小的Map集合
*/
private static List<Map<String, String>> scanFiles(String dirPath) {
List<Map<String, String>> fileList = new ArrayList<>();
File dir = new File(dirPath);
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
Map<String, String> fileInfo = new HashMap<>();
fileInfo.put("path", file.getAbsolutePath());
fileInfo.put("size", String.valueOf(file.length()));
fileList.add(fileInfo);
}
}
return fileList;
}
/**
* 将Map集合转换为JSON格式字符串
*/
private static String listToJson(List<Map<String, String>> list) {
StringBuilder json = new StringBuilder();
json.append("[");
for (Map<String, String> map : list) {
json.append("{");
for (String key : map.keySet()) {
json.append("\"").append(key).append("\":\"").append(map.get(key)).append("\",");
}
json.deleteCharAt(json.length() - 1);
json.append("},");
}
json.deleteCharAt(json.length() - 1);
json.append("]");
return json.toString();
}
/**
* 将字符串写入文件
*/
private static void writeToFile(String filePath, String content) {
try {
Path path = Paths.get(filePath);
if (!Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
Files.write(path, content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
您只需要将代码中的“指定路径”替换为您要扫描的文件夹路径和写入的txt文件路径即可。
阅读全文
相关推荐















