Java 文件操作:根据设备 ID 和日期创建文件夹并保存文件
你可以使用以下的 Java 代码来实现你的需求:
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileHandler {
public static void main(String[] args) {
String deviceId = 'your_device_id';
String id = 'your_id';
File file = findFile(deviceId);
File folder = findFolder(file, getTodayDate());
saveFile(folder, id);
}
public static File findFile(String deviceId) {
String filePath = 'D:\realRecord\' + deviceId + '.txt';
File file = new File(filePath);
if (file.exists()) {
System.out.println('File exists: ' + file.getAbsolutePath());
} else {
System.out.println('File does not exist. Creating new file: ' + file.getAbsolutePath());
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
public static File findFolder(File file, String folderName) {
String folderPath = file.getParent() + '\' + folderName;
File folder = new File(folderPath);
if (folder.exists()) {
System.out.println('Folder exists: ' + folder.getAbsolutePath());
} else {
System.out.println('Folder does not exist. Creating new folder: ' + folder.getAbsolutePath());
try {
folder.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
return folder;
}
public static void saveFile(File folder, String id) {
String filePath = folder.getAbsolutePath() + '\' + id + '.txt';
File file = new File(filePath);
try {
file.createNewFile();
System.out.println('File saved at: ' + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getTodayDate() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat('yyyyMMdd');
return sdf.format(date);
}
}
注意替换代码中的 'your_device_id' 和 'your_id' 为你的实际设备 ID 和文件夹 ID。这个程序会在控制台输出文件和文件夹的路径。
原文地址: https://www.cveoy.top/t/topic/hzwp 著作权归作者所有。请勿转载和采集!