java删除文件目录及文件_Java删除文件,目录

java删除文件目录及文件_Java删除文件,目录java删除文件目录及文件TodaywewilllookintoJavadeletefileandjavadeletedirectoryexamples.Earlierwelearnedhowtocreateafileinjava.今天,我们将研究Java删除文件和Java删除目录示例。之前我们学习了如何在java中创建文件。Java删除文件…

大家好,又见面了,我是你们的朋友全栈君。

java删除文件目录及文件

Today we will look into Java delete file and java delete directory examples. Earlier we learned how to create a file in java.

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

Java删除文件 (Java delete file)

  1. Java File delete() method can be used to delete files or empty directory/folder in java. Java file delete method returns true if file gets deleted and returns false if file doesn’t exist.

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

  2. If you are trying to delete a directory, it checks java File delete() method check if it’s empty or not. If directory is empty, it gets deleted else delete() method doesn’t do anything and return false. So in this case, we have to recursively delete all the files and then the empty directory.

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

  3. Another way to delete a non-empty directory is by using Files.walkFileTree() method. In this method, we can process all the files one by one, and call delete method on single files.

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

Java删除文件示例 (Java delete file example)

Let’s see java delete file example program.

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

package com.journaldev.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/pankaj/file.txt");
        if(file.delete()){
            System.out.println("/Users/pankaj/file.txt File deleted");
        }else System.out.println("File /Users/pankaj/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/pankaj/project");
        if(file.delete()){
            System.out.println("/Users/pankaj/project directory deleted from Project root directory");
        }else System.out.println("/Users/pankaj/project directory doesn't exist or not empty");
    }

}

Below is the output when we execute the above java delete file example program for the first time.

下面是我们第一次执行上述java delete file示例程序时的输出。

/Users/pankaj/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/pankaj/project directory doesn't exist or not empty

Note that temp directory had file.txt and it got deleted first and then directory was empty and got deleted successfully, /Users/pankaj/project was not empty and hence not deleted.

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

In the subsequent run of the same program, the output is:

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

File /Users/pankaj/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/pankaj/project directory doesn't exist or not empty

Notice that unlike createNewFile(), delete method doesn’t throw IOException.

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

Java删除目录 (Java delete directory)

Below is a simple program showing how to delete a non-empty directory. This will work if your directory contains files only.

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

package com.journaldev.files;

import java.io.File;

public class JavaDeleteDirectory {

	public static void main(String[] args) {
		File dir = new File("/Users/pankaj/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 delete directory recursively)

Earlier we had to write recursion based code to delete a directory with nested directories. But with Java 7, we can do this using Files class. Below is the code that you should use to delete a directory. It takes care of deleting nested directories too.

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

package com.journaldev.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/pankaj/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;
		   }
		});
	}
}

That’s all for java delete file and java delete directory examples.

这就是java删除文件和java删除目录示例的全部内容。

GitHub Repository.
GitHub存储库中签出更多Java IO示例。

Reference: Java NIO Files Class API Doc

参考: Java NIO文件类API文档

翻译自: https://www.journaldev.com/830/java-delete-file-directory

java删除文件目录及文件

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/134453.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(1)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号