Java删除文件,目录

时间:2020-02-23 14:34:27  来源:igfitidea点击:

今天,我们将研究Java删除文件和Java删除目录的示例。
之前我们学习了如何在Java中创建文件。

Java删除文件

  • Java File delete()方法可用于删除文件或者java中的空目录/文件夹。
    Java文件删除方法如果删除了文件,则返回true;如果文件不存在,则返回false。

  • 如果您要删除目录,它将检查java File delete()方法是否为空。
    如果目录为空,则将其删除,否则delete()方法不执行任何操作并返回false。
    因此,在这种情况下,我们必须递归删除所有文件,然后删除空目录。

  • 删除非空目录的另一种方法是使用Files.walkFileTree()方法。
    在这种方法中,我们可以一个接一个地处理所有文件,并对单个文件调用delete方法。

Java删除文件示例

让我们看一下Java删除文件示例程序。

package com.theitroad.files;

import java.io.File;

public class DeleteFileJava {

  /**
   * This class shows how to delete a File in Java
   * @param args
   */
  public static void main(String[] args) {
      //absolute file name with path
      File file = new File("/Users/hyman/file.txt");
      if(file.delete()){
          System.out.println("/Users/hyman/file.txt File deleted");
      }else System.out.println("File /Users/hyman/file.txt doesn't exist");
      
      //file name only
      file = new File("file.txt");
      if(file.delete()){
          System.out.println("file.txt File deleted from Project root directory");
      }else System.out.println("File file.txt doesn't exist in the project root directory");
      
      //relative path
      file = new File("temp/file.txt");
      if(file.delete()){
          System.out.println("temp/file.txt File deleted from Project root directory");
      }else System.out.println("File temp/file.txt doesn't exist in the project root directory");
      
      //delete empty directory
      file = new File("temp");
      if(file.delete()){
          System.out.println("temp directory deleted from Project root directory");
      }else System.out.println("temp directory doesn't exist or not empty in the project root directory");
      
      //try to delete directory with files
      file = new File("/Users/hyman/project");
      if(file.delete()){
          System.out.println("/Users/hyman/project directory deleted from Project root directory");
      }else System.out.println("/Users/hyman/project directory doesn't exist or not empty");
  }

}

下面是我们第一次执行上述java删除文件示例程序时的输出。

/Users/hyman/file.txt File deleted
file.txt File deleted from Project root directory
temp/file.txt File deleted from Project root directory
temp directory deleted from Project root directory
/Users/hyman/project directory doesn't exist or not empty

请注意,临时目录具有file.txt,并且首先被删除,然后目录为空并成功删除,/Users/hyman/project不为空,因此未删除。

在同一程序的后续运行中,输出为:

File /Users/hyman/file.txt doesn't exist
File file.txt doesn't exist in the project root directory
File temp/file.txt doesn't exist in the project root directory
temp directory doesn't exist or not empty in the project root directory
/Users/hyman/project directory doesn't exist or not empty

请注意,与createNewFile()不同,delete方法不会引发IOException。

Java删除目录

下面是一个简单的程序,显示了如何删除非空目录。
如果您的目录仅包含文件,则此方法有效。

package com.theitroad.files;

import java.io.File;

public class JavaDeleteDirectory {

	public static void main(String[] args) {
		File dir = new File("/Users/hyman/log");
		
		if(dir.isDirectory() == false) {
			System.out.println("Not a directory. Do nothing");
			return;
		}
		File[] listFiles = dir.listFiles();
		for(File file : listFiles){
			System.out.println("Deleting "+file.getName());
			file.delete();
		}
		//now directory is empty, so we can delete it
		System.out.println("Deleting Directory. Success = "+dir.delete());
		
	}

}

Java递归删除目录

之前,我们不得不编写基于递归的代码来删除带有嵌套目录的目录。
但是对于Java 7,我们可以使用Files类来实现。
下面是您用于删除目录的代码。
它也需要删除嵌套目录。

package com.theitroad.files;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class JavaDeleteDirectoryRecursively {

	public static void main(String[] args) throws IOException {
		
		Path directory = Paths.get("/Users/hyman/log");
		Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
		   @Override
		   public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
		       Files.delete(file); //this will work because it's always a File
		       return FileVisitResult.CONTINUE;
		   }

		   @Override
		   public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
		       Files.delete(dir); //this will work because Files in the directory are already deleted
		       return FileVisitResult.CONTINUE;
		   }
		});
	}
}