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删除文件目录及文件

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

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

(1)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 7k7k_leetcode 第一题

    7k7k_leetcode 第一题有 n 根长度互不相同的木棍,长度为从 1 到 n 的整数。请你将这些木棍排成一排,并满足从左侧 可以看到 恰好 k 根木棍。从左侧 可以看到 木棍的前提是这个木棍的 左侧 不存在比它 更长的 木棍。例如,如果木棍排列为 [1,3,2,5,4] ,那么从左侧可以看到的就是长度分别为 1、3 、5 的木棍。给你 n 和 k ,返回符合题目要求的排列 数目 。由于答案可能很大,请返回对 109 + 7 取余 的结果。示例 1:输入:n = 3, k = 2输出:3解释:[1,3,2], [2,3,

    2022年8月11日
    6
  • c#之splitcontainer类(接口)

    c#之splitcontainer类(接口)tcbs系统中用到,故大约了解下用法:http://msdn.microsoft.com/zh-cn/library/system.windows.forms.splitcontainer.aspx下面的代码示例演示…

    2022年7月18日
    12
  • 调用第三方接口大致流程

    调用第三方接口大致流程下面以风控为例,业务是调用第三方接口获取支付宝报告天机支付宝获取流程:1本质:中转站:前台把参数传给我,我接受参数后传给天机,天机在传给支付宝,最后获取数据,在这个过程中   我们和天机都充当的是中转站的角色。2流程:a前台传客户的基本信息参数    b后台接受参数,传给天机,天机返回淘宝的认证地址链接,后台把链接返回给前台;    c前台打开链接,进入认证页面,进行认…

    2022年6月1日
    51
  • Vue 入门教程[通俗易懂]

    Vue 入门教程[通俗易懂]Vue入门教程

    2022年5月30日
    38
  • 怎么查看线程的状态及interrupt优雅的关闭线程和interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?

    怎么查看线程的状态及interrupt优雅的关闭线程和interrupt()、interrupted()、isInterrupted()的作用以及区别在哪?示例:查看状态:刚才我们讲过,一个线程里面任务正常执行完毕,状态就是TERMINATED,就是终止状态。但是,如果我线程里面的任务一直没有执行完成,我想去终止这个线程,或者我给点信息给到线程里,告诉线程我想终止结束呢!所以我可以强制去关闭线程:线程提供一个stop方法,该方法不建议使用,已经过时了!!因为stop是强行关闭线程,线程里面的任务都不在执行,不管线程的任务是否执行成功与否,就算执行到一半也会强制关闭!导致很多不可控制的结果,比如支付付一半等等!!所以我们要需要去优雅的关闭。什么叫做优雅关

    2025年7月29日
    4
  • 移动通信概述-架构篇[通俗易懂]

    移动通信概述-架构篇[通俗易懂]移动通信概述-架构篇

    2022年9月21日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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