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)


相关推荐

  • mysql取分组后最新的一条数据_mysql分组后取最大时间

    mysql取分组后最新的一条数据_mysql分组后取最大时间mysql取分组后最新的一条记录,下面两种方法.一种是先筛选出最大和最新的时间,在连表查询.一种是先排序,然后在次分组查询(默认第一条),就是最新的一条数据了#select*fromt_assistant_articleasa,(selectmax(base_id)asbase_id,max(create_time)ascreate_timefromt_assista

    2022年10月30日
  • java开发工程师的简历怎么写(应聘网络工程师简历)

    这是一篇我比较想看到的简历指导的文章。但是我比较反对简历造假。我觉得会什么写什么把。Java就业指导  想要成为合格的Java程序员或工程师到底需要具备哪些专业技能,面试者在面试之前到底需要准备哪些东西呢?本文陈列的这些内容既可以作为个人简历中的内容,也可以作为面试的时候跟面试官聊的东西,你可以把这些内容写到你的简历中,当然更需要的是你在面试的时候向面试官展示这些专业技能。相信此文…

  • 40-50岁的男人喜欢什么样的女人呢?

    40-50岁的男人喜欢什么样的女人呢?悟空问答里有个热门问题:40-50岁的男人喜欢什么样的女人呢?答案多姿多彩,有理有据互补的女人有安全感的女人经济独立的女人性爱和谐的女人心态成熟的女人知书达理的女人会过生活的女人能好好聊天的女人温柔体贴的女人…………认为:无论男人是20岁、30岁、40岁、50岁、60岁、70岁、80岁、90岁、100岁还是200岁,他们都喜欢年轻漂亮的小姑娘,同意的转起。

  • mac的内核_Mac编程

    mac的内核_Mac编程MAC内核编程指南-综述等

  • strsep的作用

    strsep的作用在下面这个code中通过strsep将p表示的字符串一“,”分开,例如12,34,56.会先返回12,然后是34,最后是56while((id=strsep(&p,”,”)))我们看看strsep的实现char*strsep(char**s,constchar*ct){   char*sbegin=*s;   char*end;  

    2022年10月30日
  • 用C#编程的建议建议收藏

    1.如果可能尽量使用接口来编程.NET框架包括类和接口,在编写程序的时候,你可能知道正在用.NET的哪个类。然而,在这种情况下如果你用.NET支持的接口而不是它的类来编程时,代码会变得更加稳定、可用

    2021年12月21日

发表回复

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

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