Table of Contents
File类
File类常用的构造方法
查看文件的相应信息
遍历目录下的文件
文件过滤器
对子目录进行遍历
删除文件及目录
Home Java javaTutorial Java File class common methods and file filter example analysis

Java File class common methods and file filter example analysis

Apr 29, 2023 am 08:31 AM
java file

File类

File类用于封装一个路径,这个路径可以是从系统盘符开始的绝对路径,也可以是相对于当前目录的相对路径,File类内部封装的路径可以指向一个文件,也可以指向一个目录,在File类中提供了针对这些目录或文件的一些常规操作。

File类常用的构造方法

 File(String pathname)//通过指定的一个字符串类型的文件路径来创建一个新的File对象
 File(String parent,String child)//根据指定的一个字符串类型的父路径和一个字符串类型的子路径创建一个File对象
 File(File parent,String child)//根据指定的File类的父路径和字符串类型的子路径创建一个File对象

查看文件的相应信息

package JS;
 import java.io.File;
 public class XX {
     public static void main(String[] args) {
         File file=new File("example.txt");
         //获取文件名称
         System.out.println("文件名称:"+file.getName());
         //获取文件的相对路径
         System.out.println("文件的相对路径:"+file.getPath());
         //获取文件的绝对路径
         System.out.println("文件的绝对路径:"+file.getAbsolutePath());
         //获取文件的父路径
         System.out.println("文件的父路径:"+file.getParent());
         //判断文件是否可读
         System.out.println(file.canRead() ?"文件可读":"文件不可读");
         //判断文件是否可写
         System.out.println(file.canWrite() ?"文件可写":"文件不可写");
         //判断是否是同一个文件
         System.out.println(file.isFile() ?"是一个文件":"不是一个文件");
         //判断是否是同一个目录
         System.out.println(file.isDirectory() ?"文件是一个目录":"文件不是一个目录");
        //得到文件最后的修改时间
         System.out.println("最后修改时间为:"+file.lastModified());
         //得到文件的大小
         System.out.println("文件的大小为:"+file.length()+"bytes");
         //是否成功删除文件
         System.out.println("是否成功删除文件"+file.delete());
     }
 }
Copy after login

Java File class common methods and file filter example analysis

遍历目录下的文件

通过list()方法可以遍历某个指定目录下的所有文件名称

 package JhiShi;
 import java.io.File;
 public class Example01 {
     public static void main(String[] args) throws Exception{
         File file=new File("C:\\Users\\lenovo\\IdeaProjects\\java se");
         if(file.isDirectory()){
             String[] names=file.list();
             for (String name:names){
                 System.out.println(name);
             }
         }
     }
 }
Copy after login

Java File class common methods and file filter example analysis

先通过File类里面的isDirectory()方法判断路径指向的是否为存在的目录,存在就调用list()方法,并且获得String类型的数组names,数组中包含这个目录下的所有文件的文件名,然后循环遍历数组的names,依次打印出每个文件的名字。

文件过滤器

 package JhiShi;
 import java.io.File;
 import java.io.FilenameFilter;
 public class Example02 {
     public static void main(String[] args) throws Exception{
         File file=new File("C:\\Users\\lenovo\\IdeaProjects\\java se");
         FilenameFilter filter=new FilenameFilter() {
             @Override
             public boolean accept(File dir, String name) {
                 File currFile=new File(dir,name);
                 if(currFile.isFile()&&name.endsWith(".txt")){
                     return true;
                 }else{
                     return false;
                 }
             }
         };
         if(file.exists()){
             String[] lists=file.list(filter);
             for (String name:lists){
                 System.out.println(name);
             }
         }
     }
Copy after login

Java File class common methods and file filter example analysis

对子目录进行遍历

 package JhiShi;
 import java.io.File;
 public class Example03 {
     public static void main(String[] args) throws Exception{
         File file=new File("C:\\Users\\lenovo\\IdeaProjects\\java se");
         fileDir(file);
     }
     public static void fileDir(String[] args) {
         File[]files=dir.listFiles();
         for (File file:files){
             if(file.isDirectory()){
                 fileDir(file);
             }
             System.out.println(file.getAbsoluteFile());
         }
     }
 }
Copy after login

通过一个静态方法fileDir(),用于接收一个表示目录的File对象,先调用listFile()方法把该目录下所有的子目录和文件存到一个File类型的数组files中,然后遍历数组files,并且对遍历对象进行判断,如果是目录就从新调用fileDir()方法进行递归,如果是文件则输出文件的路径。

删除文件及目录

 package JhiShi;
 import java.io.File;
 public class Example03 {
     public static void main(String[] args) {
         File file=new File("C:\\ABC");
         deleteDir(file);  
     }
     public static void deleteDir(String[] args) {
         if(dir.exists){
             File[]files=dir.listFiles();
             for(File file:files){
                 if(files.isDirectory()){
                     deleteDir(file);
                 }else{
                     file.delete();
                 }
             }
             dir.delete();
         }
     }
 }
Copy after login

定义了一个删除目录的静态方法deleteDir()来接收一个File类型的参数,调用listFiles()方法把这个目录下所有的子目录和文件保存到一个File类型的数组files中,然后遍历files,如果是目录从新调用deleteDir()方法进行递归,如果是文件则直接调用File的delete()方法删除,当删除完这个目录下的所有文件时,再删除这个目录。

注意:Java删除目录是从虚拟机直接删除而不是回收站,一旦删除无法恢复

The above is the detailed content of Java File class common methods and file filter example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles