Java 移动文件到指定目录

Java 移动文件到指定目录:

public void moveFile(){
        String fromPath="D:\\test\\1.mp4";
        String toPath="D:\\totest";
        System.out.println("移动文件:从路径 " + fromPath + " 移动到路径 " + toPath);
        File file = new File(fromPath);
            if (file.isFile()){  
                File toFile=new File(toPath+"\\"+file.getName());  
                if (toFile.exists()){  
                   System.out.println("文件已存在");
                }
                else{
                    file.renameTo(toFile); 
                    System.out.println("移动文件成功");
                } 
            }         
        }
     }

 

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
移动文件并保留其创建日期,您可以使用Java中的NIO库中的Files.move()方法。此方法允许您指定移动文件以及目标位置,并保留原始文件的属性,包括创建日期。 以下示例演示如何将文件从源目录移动到目标目录,并保留其创建日期: ```java import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.time.Instant; public class MoveFileExample { public static void main(String[] args) throws Exception { String sourcePath = "C:\\source\\file.txt"; String targetPath = "C:\\target\\file.txt"; Path source = Paths.get(sourcePath); Path target = Paths.get(targetPath); // 获取原始文件的创建日期 BasicFileAttributes attr = Files.readAttributes(source, BasicFileAttributes.class); FileTime creationTime = attr.creationTime(); // 移动文件并保留创建日期 Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); Files.getFileAttributeView(target, BasicFileAttributes.class).setTimes(creationTime, null, null); } } ``` 在上面的示例中,我们首先获取源文件的路径和目标路径。接下来,我们使用Files.readAttributes()方法获取源文件的创建日期。然后,我们使用Files.move()方法将文件移动到目标位置,并使用StandardCopyOption.REPLACE_EXISTING选项覆盖现有文件(如果存在)。最后,我们使用Files.getFileAttributeView()方法获取目标文件的属性视图,并使用setTimes()方法设置创建日期。这将保留原始文件的创建日期,而不会更改它。 请注意,此示例中的操作可能会抛出异常,因此您应该在代码中使用try-catch语句或将异常传播到调用代码中进行处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值