Java 方法:保存 JSON 文件到指定设备和 ID 目录
以下是一个 Java 方法,用于将 JSON 文件保存到以设备 ID 和 ID 命名的目录中。该方法会根据设备 ID 和日期创建必要的文件夹,并将 JSON 文件保存到指定 ID 文件夹中。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class FileManager {
public static void saveJsonFile(String deviceId, String id, File jsonFile) {
String baseDirPath = "D:\realRecord";
String deviceDirPath = baseDirPath + "\" + deviceId;
String todayDirPath = deviceDirPath + "\" + getFormattedTodayDate();
String idDirPath = todayDirPath + "\" + id;
// 检查设备文件夹是否存在,如果不存在则创建
File deviceDir = new File(deviceDirPath);
if (!deviceDir.exists()) {
deviceDir.mkdir();
}
// 检查今天日期的文件夹是否存在,如果不存在则创建
File todayDir = new File(todayDirPath);
if (!todayDir.exists()) {
todayDir.mkdir();
}
// 检查id文件夹是否存在,如果不存在则创建
File idDir = new File(idDirPath);
if (!idDir.exists()) {
idDir.mkdir();
}
// 复制json文件到id文件夹
Path jsonFilePath = jsonFile.toPath();
Path targetPath = new File(idDirPath + "\" + jsonFile.getName()).toPath();
try {
Files.copy(jsonFilePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getFormattedTodayDate() {
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
return today.format(formatter);
}
}
你可以使用以下代码调用该方法:
public class Main {
public static void main(String[] args) {
String deviceId = "your_device_id";
String id = "your_id";
File jsonFile = new File("path_to_your_json_file.json");
FileManager.saveJsonFile(deviceId, id, jsonFile);
}
}
请确保将'your_device_id'替换为实际的设备 ID,'your_id'替换为实际的 ID,'path_to_your_json_file.json'替换为实际的 JSON 文件路径。
原文地址: https://www.cveoy.top/t/topic/hyyO 著作权归作者所有。请勿转载和采集!