Java File class common methods and file filter example analysis
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()); } }
遍历目录下的文件
通过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); } } } }
先通过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); } } }
对子目录进行遍历
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()); } } }
通过一个静态方法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(); } } }
定义了一个删除目录的静态方法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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In Go, range is used to iterate over data types and return corresponding values: 1. For slices and arrays, range returns index and element copy; 2. Unwanted indexes or values can be ignored using _; 3. For maps, range returns keys and values, but the iteration order is not fixed; 4. For strings, range returns rune index and characters (rune type), supporting Unicode; 5. For channels, range continues to read values until the channel is closed, and only a single element is returned. Using range can avoid manually managing indexes, making iteratives simpler and safer.

Use meaningful naming: variables such as intdaysSinceModification; methods such as getUserRolesByUsername() to make the code intention clear; 2. Functions should be small and do only one thing: for example, createUser() is split into single responsibility methods such as validateRequest() and mapToUser(); 3. Reduce comments and write self-interpretation code: Use userHasPrivilegedAccess() instead of redundant comments; 4. Handle errors elegantly: do not ignore exceptions, use try-with-resources to automatically manage resources; 5. Follow the "Boy Scout Rules": optimize variables every time you modify

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

There is an essential difference between JavaScript's WebWorkers and JavaThreads in concurrent processing. 1. JavaScript adopts a single-thread model. WebWorkers is an independent thread provided by the browser. It is suitable for performing time-consuming tasks that do not block the UI, but cannot operate the DOM; 2. Java supports real multithreading from the language level, created through the Thread class, suitable for complex concurrent logic and server-side processing; 3. WebWorkers use postMessage() to communicate with the main thread, which is highly secure and isolated; Java threads can share memory, so synchronization issues need to be paid attention to; 4. WebWorkers are more suitable for front-end parallel computing, such as image processing, and

The single responsibility principle (SRP) requires a class to be responsible for only one function, such as separating the saving and mail sending in order processing; 2. The opening and closing principle (OCP) requires opening and closing for extensions and closing for modifications, such as adding new graphics without modifying the calculator; 3. The Richter replacement principle (LSP) requires that subclasses can replace the parent class without destroying the program, such as using independent classes to avoid behavior abnormalities caused by square inheritance rectangles; 4. The interface isolation principle (ISP) requires that clients should not rely on unwanted interfaces, such as splitting the multi-function device interface to independent printing, scanning, and fax interfaces; 5. The dependency inversion principle (DIP) requires that high-level modules do not rely on low-level modules, and both rely on abstraction, such as OrderService depends on Data

GraphQL can be easily integrated in SpringBoot through official support. 1. Use spring-boot-starter-graphql to add dependencies; 2. Define the schema.graphqls file under resources to declare Query and Mutation; 3. Use @Controller to cooperate with @QueryMapping and @MutationMapping to achieve data acquisition; 4. Enable GraphiQL interface testing API; 5. Follow best practices such as input verification, N 1 query prevention, security control, etc., and ultimately implement a flexible and efficient client-driven API.

Resilience4j improves the flexibility of Java microservices through circuit breakers, current limiting, retry and other mechanisms. 1. Use circuit breakers to prevent cascade failures and prevent requests from being sent when services fail frequently; 2. Use current limit control to control concurrent access to avoid sudden traffic overwhelming downstream services; 3. Respond to temporary errors through retry mechanisms, but avoid invalid retry and resource waste; 4. Multiple strategies can be used in combination to enhance the overall resilience of the system, but attention should be paid to the mutual influence between policies. Properly configuring these functions can significantly improve the stability and fault tolerance of distributed systems.

ProjectLoomintroducesvirtualthreadstosolveJava’sconcurrencylimitationsbyenablinglightweight,scalablethreading.1.VirtualthreadsareJVM-managed,low-footprintthreadsthatallowmillionsofconcurrentthreadswithminimalOSresources.2.Theysimplifyhigh-concurrency
