Java File Move moveTo(File file, String distDir)

Here you can find the source of moveTo(File file, String distDir)

Description

move To

License

Apache License

Declaration

public static boolean moveTo(File file, String distDir) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static boolean moveTo(File file, String distDir) {
        String path = parsePath(distDir);
        checkDir(path);//  w w  w  . j a  v a2s .  com
        String filePath = (path.endsWith(File.separator)) ? path + file.getName()
                : path + File.separator + file.getName();
        return file.renameTo(new File(filePath));
    }

    private static String parsePath(String distDir) {
        Pattern parseReg = Pattern.compile("%d\\{(.*?)\\}");
        Matcher m = null;
        CharSequence inputStr = distDir.subSequence(0, distDir.length());
        m = parseReg.matcher(inputStr);

        StringBuffer sb = new StringBuffer();
        boolean found = m.find();
        while (found) {
            String timeStr = new SimpleDateFormat(m.group(1)).format(new Date());
            m.appendReplacement(sb, timeStr);
            found = m.find();
        }
        return m.appendTail(sb).toString();
    }

    private static void checkDir(String path) {
        File dist = new File(path);
        if (dist.exists()) {
            if (!dist.isDirectory()) {
                dist.renameTo(new File(dist.getPath() + ".swp." + System.currentTimeMillis()));
                dist.mkdir();
            }
        } else {
            dist.mkdir();
        }
    }
}

Related

  1. move(File from, File to, boolean overwrite)