java - 用java移动文件

标签 java

我正在尝试使用此 java 代码移动文件,它可以找到该文件但不能移动它,只是删除我要将其移动到的目录。

public void ch() throws Exception{
   if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
       java.io.File file = FC.getSelectedFile();
       Scanner input = new Scanner(file);
       System.out.println(file);

       Path source = Paths.get(file + "");
       Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2");       
       try {
           Files.move(source, target, REPLACE_EXISTING);
       } catch (IOException e){ 
           System.out.println("Failed to move the file");
       }
   }else{
       System.out.println("?");
   }
}

最佳答案

在目标路径末尾添加文件名,如下所示: 您可以使用 File.ranameTo() 方法移动文件,如下所示:

file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));

在您的示例中:

public void ch() throws Exception{
       if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
           java.io.File file = FC.getSelectedFile();      
           try {
                 file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
           } catch (Exception e){ 
               System.out.println("Failed to move the file");
           }
       }else{
           System.out.println("?");
       }
    }

关于java - 用java移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379142/

相关文章:

java - 如何借助NotificationListnerService在通知中按下“标记为已读”按钮?

java - JAX-RS( Jersey )和 Jackson 未正确序列化 LocalDate

java - 为 jdk7 分析 java 应用程序的方法

java - 如何使用 Jackson 序列化为 java.util.List 和 java.util.Map

java - Windows 区分大小写导致麻烦,无法将 Java 项目包含到 Eclipse

java - 使用 play 2 war 和 play 2.2.1

java - 在 eclipse 中配置 FindBugs

java - 如何确定 Guava 缓存中是否存在某个键,以便我不覆盖它?

java - Google Guice 绑定(bind)问题

java - JFrame GridBagLayout 组件定位