-2

我需要删除的文件夹是从我的程序创建的文件夹。每台电脑上的目录都不一样,所以我使用的文件夹代码是

userprofile+"\\Downloads\\Software_Tokens"

里面会有文件,所以我想我需要递归删除它。我在这里查看了一些示例,但它从不接受我的路径。该路径在代码中作为环境变量可以正常工作,因为我为它添加了代码

static String userprofile = System.getenv("USERPROFILE");

那么有人可以向我展示我的路径插入的代码吗?

4

2 回答 2

1

如果您的目录不为空,您可以使用Apache Commons IO API的方法deleteDirectory(File file)

String toDelete = userprofile + File.separator + "Downloads" + 
        File.separator + "Software_Tokens";
FileUtils.deleteDirectory(new File(toDelete));

请注意与系统相关的/or并改为使用。\File.separator

于 2012-06-27T07:34:03.050 回答
0

如果您不想使用 apache 库!您可以递归地执行此操作。

  String directory = userprofile + File.separator + "Downloads" + File.separator + "Software_Tokens";
  if (!directory.exists()) {
      System.out.println("Directory does not exist.");
      System.exit(0);
  } else {
      try {
          delete(directory);
      } catch (IOException e) {
          e.printStackTrace();
          System.exit(0);
      }
  }
  System.out.println("Done");
  }
  public static void delete(File file)
   throws IOException {
      if (file.isDirectory()) {
          //directory is empty, then delete it
          if (file.list().length == 0) {
              file.delete();
              System.out.println("Directory is deleted : " + file.getAbsolutePath());
          } else {
              //list all the directory contents
              String files[] = file.list();
              for (String temp: files) {
                  //construct the file structure
                  File fileDelete = new File(file, temp);

                  //recursive delete
                  delete(fileDelete);
              }
              //check the directory again, if empty then delete it
              if (file.list().length == 0) {
                  file.delete();
                  System.out.println("Directory is deleted : " + file.getAbsolutePath());
              }
          }
      } else {
          //if file, then delete it
          file.delete();
          System.out.println("File is deleted : " + file.getAbsolutePath());
      }
于 2012-06-27T08:18:23.433 回答