Java程式:將文件以其最後修改時刻命名

package com.papwin;

import java.io.Console;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class RenameFiles
{
    public static void main(String[] args)
    {
        Console console = System.console();
        if(console == null)
        {
            System.out.println("獲取主控臺對象失敗!");
            System.exit(1);
        }
        String path;
        do
        {
            path = console.readLine("設定工作目錄:");
        }
        while(path.trim().equals(""));
        while(true)
        {
            Path workPath = Paths.get(path.trim());
            try(DirectoryStream<Path> stream = Files.newDirectoryStream(workPath))
            {
                String lastModifiedTime, oldName, extName;
                for(Path oldPath : stream)
                {
                    console.format("正在重命名 %s ...%n", oldPath.toAbsolutePath());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(Files.getLastModifiedTime(oldPath, LinkOption.NOFOLLOW_LINKS).toMillis());
                    lastModifiedTime = new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
                    extName = (oldName = oldPath.getFileName().toString()).substring(oldName.lastIndexOf("."));
                    Path newPath = Paths.get(oldPath.getParent() + "/" + lastModifiedTime + extName), tmpPath = newPath;
                    for(int no = 1; Files.exists(tmpPath, LinkOption.NOFOLLOW_LINKS); ++no)
                    {
                        tmpPath = Paths.get(new StringBuffer(newPath.toString()).insert(newPath.toString().lastIndexOf('.'), String.format("(%d)", no)).toString());
                    }
                    newPath = tmpPath;
                    Files.move(oldPath, newPath);
                }
            }
            catch(IOException e)
            {
                console.writer().write(e.getMessage());
            }
            console.readLine("按下回車鍵繼續...");
        }
    }
}

在〈Java程式:將文件以其最後修改時刻命名〉中有 2 則留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *