java批量修改照片文件名为拍摄时间(Exif里获取)
手机里的照片,一年整理一次。拍摄时间在Exif中获取,若获取失败则使用创建时间。
package auto; import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.metadata.Metadata; import com.drew.metadata.exif.ExifSubIFDDirectory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * @author rll * @description: 批量修改照片(jpg)时间 * @date 2026/8/7 */ public class PicRename { public static void main(String[] args) { //设置为GMT+8,小时时间对不上,特意改为GMT TimeZone.setDefault(TimeZone.getTimeZone("GMT")); //TODO 修改为你要处理的文件夹路径 String folderPath = "F:\\test"; File folder = new File(folderPath); if (!folder.exists() || !folder.isDirectory()) { System.out.println("文件夹不存在或不是一个目录: " + folderPath); return; } File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg")); if (files == null || files.length == 0) { System.out.println("文件夹内没有 .jpg 文件"); return; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss"); // EXIF 时间通常为本地时间,无需时区转换 sdf.setTimeZone(TimeZone.getDefault()); for (File file : files) { try { Date shootingTime = getShootingTime(file); String newName = sdf.format(shootingTime) + ".jpg"; File newFile = new File(folder, newName); // 处理重名:若文件已存在(且不是同一文件),添加序号 if (newFile.exists() && !file.getCanonicalPath().equals(newFile.getCanonicalPath())) { newFile = makeUniqueFile(folder, sdf.format(shootingTime), ".jpg"); } if (file.renameTo(newFile)) { System.out.println("重命名成功: " + file.getName() + " -> " + newFile.getName()); } else { System.out.println("重命名失败: " + file.getName()); } } catch (Exception e) { System.err.println("处理文件失败: " + file.getName() + ", 原因: " + e.getMessage()); } } } /** * 优先从 EXIF 获取拍摄时间,若获取失败则使用文件修改时间 */ private static Date getShootingTime(File file) throws IOException { try { Metadata metadata = ImageMetadataReader.readMetadata(file); ExifSubIFDDirectory exifDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class); if (exifDir != null) { Date date = exifDir.getDateOriginal(); System.out.println("拍摄时间:"+exifDir); if (date != null) { return date; } } } catch (ImageProcessingException e) { // 无法解析 EXIF,使用文件时间 } // Fallback: 使用文件最后修改时间 Path path = Paths.get(file.getAbsolutePath()); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); FileTime fileTime = attrs.lastModifiedTime(); return new Date(fileTime.toMillis()); } /** * 生成不重名的文件,命名格式为 baseName_序号.jpg */ private static File makeUniqueFile(File directory, String baseName, String extension) { int count = 1; File candidate; do { candidate = new File(directory, baseName + "_" + count + extension); count++; } while (candidate.exists()); return candidate; } }