java - 如何在一个文件夹中的多个文件中附加日期和时间,同时将其移动到另一个文件夹

标签 java

public static void main(String[] args) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();

源文件夹

     File source = new File("D:\\A1\\"); 
     File dest = new File("D:\\A2\\");
     File[] files = source.listFiles(); 


    for (File file: source.listFiles()){
               String x=(source+"\\"+file.getName());
         String y=(dest + "\\"+ file.getName());

     File f1 = new File(x);
     f1.renameTo(new File(y));      

     }

此代码正在将文件从源文件夹移动到目标文件夹,但我希望文件何时移动到目标文件夹。它附加系统日期及其名称 请帮忙

最佳答案

您需要将时间戳附加到文件名中,最好在扩展名之前。

请注意,操作系统可能不允许某些字符出现在文件名中,例如冒号和斜杠可能无法在 Windows 上使用,因此您需要找到它们的替代品。

还需要检查 renameTo 的返回值检查文件是否真的被移动。

returns true if and only if the renaming succeeded; false otherwise

你可以尝试这样的事情:

public static void main(String[] args) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    String ts = dateFormat.format(date);

    File source = new File("D:\\A1\\");
    File dest = new File("D:\\A2\\");

    for (File file : source.listFiles()) {
        String x = (source + "\\" + file.getName());
        String y = (dest + "\\" + addTimestamp(file.getName(), ts));

        File f1 = new File(x);
        if(f1.renameTo(new File(y))){
            System.out.println("moved: " + y);
        } else {
            System.out.println("unable to move: " + y);
        }
    }
}

private static String addTimestamp(String name, String ts) {
    int lastIndexOf = name.lastIndexOf('.');
    return (lastIndexOf == -1 ? 
            name + "_" + ts 
            : 
            name.substring(0, lastIndexOf) + "_" + ts + 
            name.substring(lastIndexOf))
             .replaceAll("[\\/:\\*\\?\"<>| ]", "_");
}

最后为了更好地移动文件,请使用 Files#move正如 renameTo 本身的 javadoc 所暗示的那样。

关于java - 如何在一个文件夹中的多个文件中附加日期和时间,同时将其移动到另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23734354/

相关文章:

java - 以编程方式检索方法的参数和值

java - "The value of the local variable is not used."

java - 如何将全局变量设置为 JSLint 以忽略整个文件集?

java - 为 jButton 添加属性 [JAVA]

Java String == 运算符与字符串文字

java - Spark (JAVA): how to read and save data file from the http body(Audio file)?

java - 嵌套同步方法的开销

java: 将文件解压成字符串太慢

Java:连接数据库并返回查询结果

java - 未过期的谷歌日历api channel java