【问题标题】:Displaying Files and Directories and moving them in Java显示文件和目录并在 Java 中移动它们
【发布时间】:2012-10-11 07:28:36
【问题描述】:
我想创建一个应用程序,将本地文件系统目录中的选定文件移动到另一个“预选位置”并返回到它来自的目录。我希望它是可视的,例如我有一个 JFrame。在这个 JFrame 里面有 2 个“windows”,一个是来自 /home 或任何地方的当前本地文件系统,它有文件夹,当你点击它们时会显示它们的子文件夹和可以点击的文件等(就像你打开时一样Windows 中的资源管理器或 Mac 中的 finder)。右侧的另一个窗口是一个已预先选择的空目录,其中没有显示任何文件。
在这些窗口之间有两个按钮。一个有一个'->'箭头。其他“
一个足够简单的 gui,但我不确定如何开始编码,或者在显示所有文件并选择它们方面最好的方法。
有什么想法吗?
欧登
【问题讨论】:
标签:
java
file
user-interface
filesystems
directory
【解决方案1】:
对于文件移动,请考虑在File 类中使用renameTo 方法。你的代码应该是这样的,
File file = new File(presentLocation);
String newLocation = " NEW_LOCATION "; // your new location
boolean isFileMoved = file.renameTo(new File(newLocation+file.getName())); //tells you whether file is moved or not.
if (isFileMoved) {
System.out.println("File is successfully moved to "+newLocation);
} else {
System.out.println("File is not moved to "+newLocation);
}
将文件用于将文件的旧位置移动到新位置,反之亦然。使用 UI 在您的后端实现这一点。
【解决方案2】:
这是我深入遍历目录以进行递归删除的代码。
您可以使用它来“显示”和导航。
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}