我正在尝试使用此 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/