Java SE入门及基础(43)

目录

File类

1. File类的作用

2. File类的使用

常用构造方法

 示例

常用方法

1.获取文件相关信息

示例

2.文件相关的判断

示例

3.文件列表相关

示例

3. 递归

示例

1.使用递归求1~100的累加和。

2.使用递归打印文件夹下所有文件信息

练习

思考:如何删除一个文件夹?

Java SE文章参考:Java SE入门及基础知识合集-CSDN博客


File

1. File类的作用

        java.io.File 类是对存储在磁盘上的文件信息的一个抽象表示。主要用于文件的创建、查找和删除。

2. File类的使用

常用构造方法
public File ( String pathname ); // 通过将给定的字符串路径名转换为抽象路径名来创建 File 实例
public File ( String parent , String child ); // 通过给定的字符父级串路径和字符串子级路径来创建File 实例
public File ( File parent , String child ); // 通过父级抽象路径名和字符串子路径创建 File 实例。
 示例
package com . we . file ;
import java . io . File ;
/**
* File 类构造方法的使用
*/
public class Example1 {
        public static void main ( String [] args ) {
                File file1 = new File ( "F:\\a\\b\\c.txt" );
                File file2 = new File ( "F:\\a\\b" , "c.txt" );
                File parent = new File ( "F:\\a\\b" );
                File file3 = new File ( parent , "c.txt" );
        }
}
常用方法
1.获取文件相关信息
// 绝对路径:带有盘符的路径称之为绝对路径
// 相对路径:不带盘符的路径称之为相对路径,相对路径相对于当前工程来定位的。
public String getAbsolutePath (); // 获取文件的绝对路径
public String getName (); // 获取文件的名字
public String getPath (); // 获取文件的路径
public File getParentFile (); // 获取文件的父文件
public String getParent (); // 获取文件的父文件路径
public long length (); // 获取文件的大小
public long lastModified (); // 获取文件最后修改时间
示例
package com . we . file ;
import java . io . File ;
public class Example2 {
        public static void main ( String [] args ) {
                File file = new File ( "F:\\a\\b\\c.txt" );
                //获取文件的绝对路径
                String absPath = file . getAbsolutePath ();
                System . out . println ( absPath );
                //获取文件的路径,可能是相对路径,也可能是绝对路径
                String path = file . getPath ();
                System . out . println ( path );
                String name = file . getName (); // 获取文件名
                System . out . println ( name );
                //获取文件的父级文件夹对象
                File parentFile = file . getParentFile ();
                System . out . println ( parentFile . getPath ());
                //获取文件的父级路径
                String parentPath = file . getParent ();
                System . out . println ( parentPath );
                //获取文件的大小,单位是字节
                long length = file . length ();
                System . out . println ( length );
                //获取文件的最后修改时间
                long lastUpdateTime = file . lastModified ();
                System . out . println ( lastUpdateTime );
                //获取系统当前时间:单位毫秒
                long currentTime = System . currentTimeMillis ();
                System . out . println ( currentTime );
                File file1 = new File ( "chapter16\\c.txt" );
                System . out . println ( file1 . getAbsolutePath ());
                System . out . println ( file1 . getPath ());
        }
}
2.文件相关的判断
public boolean canRead (); // 是否可读
public boolean canWrite (); // 是否可写
public boolean exists (); // 是否存在
public boolean isDirectory (); // 是否是目录
public boolean isFile (); // 是否是一个正常的文件
public boolean isHidden (); // 是否隐藏
public boolean canExecute (); // 是否可执行
public boolean createNewFile () throws IOException ; // 创建新的文件
public boolean delete (); // 删除文件
public boolean mkdir (); // 创建目录,一级
public boolean mkdirs (); // 创建目录,多级
public boolean renameTo ( File dest ); // 文件重命名
示例
package com . we . file ;
import java . io . File ;
import java . io . IOException ;
/**
* 文件判断
*/
public class Example3 {
        public static void main ( String [] args ) {
                File file = new File ( "F:\\record\\stu.txt" );
                //判断文件是否可读
                boolean readable = file . canRead ();
                System . out . println ( " 文件是否可读: " + readable );
                //判断文件是否可写
                boolean writable = file . canWrite ();
                System . out . println ( " 文件是否可写: " + writable );
                //判断文件是否存在
                boolean exists = file . exists ();
                System . out . println ( " 文件是否存在: " + exists );
                //判断文件是否是目录
                boolean isDirectory = file . isDirectory ();
                System . out . println ( " 文件是否是目录: " + isDirectory );
                File parent = file . getParentFile ();
                System . out . println ( " 父级文件是否是目录: " + parent . isDirectory ());
                //判断文件是否是隐藏文件
                boolean hidden = file . isHidden ();
                System . out . println ( " 文件是否是隐藏文件: " + hidden );
                //判断文件是否可执行
                boolean executable = file . canExecute ();
                //所谓的可执行文件,是指双击之后有反应的文件都称之为可执行文件
                System . out . println ( " 文件是否可执行: " + executable );
                File newFile = new File ( "F:\\test\\stu\\new.txt" );
                File parentFile = newFile . getParentFile ();
                if ( ! parentFile . exists ()){ // 通常会与创建目录的方法配合使用
                        //创建父级目录,但只能创建一级
                        // parentFile.mkdir();
                        //创建多级父级目录
                        parentFile . mkdirs ();
                }
                if ( ! newFile . exists ()){
                        try {
                                //创建文件时,必须保证改文件的父级目录存在,否则,创建将报IO异常
                                boolean success = newFile . createNewFile ();
                                System . out . println ( " 文件创建是否成功: " + success );
                        } catch ( IOException e ) {
                                e . printStackTrace ();
                        }
                }
                boolean deleteSuccess = file . delete ();
                System . out . println ( " 文件删除是否成功: " + deleteSuccess );
                //删除文件夹时,必须保证文件夹中没有任何文件,也就是保证文件夹是空的
                boolean deleteFolderSuccess = parentFile . delete ();
                System . out . println ( " 文件夹删除是否成功: " + deleteFolderSuccess );
                File renameDest = new File ( "F:\\test\\a.txt" );
                //文件重命名至目标文件夹时,必须保证目标文件夹存在。重命名操作成功后,原来的文件就移动过去了。
                boolean renameSuccess = newFile . renameTo ( renameDest );
                System . out . println ( " 文件重命名是否成功: " + renameSuccess );
        }
}
删除文件夹时必须保证文件夹为空,否则将删除失败
3.文件列表相关
public File [] listFiles (); // 列出文件夹下所有文件
public File [] listFiles ( FileFilter filter ); // 列出文件夹下所有满足条件的文件
示例
package com . we . file ;
import java . io . File ;
import java . io . FileFilter ;
/**
* 文件列表
*/
public class Example4 {
        public static void main ( String [] args ) {
                File directory = new File ( "F:\\study\\java" );
                //列出文件夹中所有文件
                File [] files = directory . listFiles ();
                //需要做非空判断,因为目录可能是非法的,也就是可能不存在
                if ( files != null ){
                        // for(int i=0; i<files.length; i++){
                        // File file = files[i];
                        // }
                        // for(File file: files){//增强for循环
                                // System.out.println(file.getPath());
                        // }
                }
                File folder = new File ( "F:\\Idea\\IntelliJ IDEA 2020.1\\bin" );
                        // class A implements FileFilter{
    
                         // @Override
                        // public boolean accept(File pathname) {
                                // return false;
                        // }
                // }
                //匿名内部类 => 相当于将类的名字隐藏起来
                FileFilter filter = new FileFilter () {
                //表示接受文件的条件
                        @Override
                        public boolean accept ( File file ) {
                                String name = file . getName (); // 获取文件名,也包含后缀在内
                                //返回文件名是否以.ext结尾
                                return name . endsWith ( ".exe" ); //startsWith("hello") 检测字符串是否hello 开始
                        }
                };
                File [] childFiles = folder . listFiles ( filter );
                if ( childFiles != null ){
                        for ( File file : childFiles ){
                                System . out . println ( file . getPath ());
                        }
                }
        }
}

3. 递归

  • 在方法内部再调用自身就是递归。递归分为直接递归和间接递归。
  • 直接递归就是方法自己调用自己。
  • 间接递归就是多个方法之间相互调用,形成一个闭环,从而构成递归。
  • 使用递归时必须要有出口,也就是使递归停下来。否则,将导致栈内存溢出。
package com . we . file ;
import java . util . Scanner ;
/**
* 递归
*/
public class Example5 {
        private static Scanner sc = new Scanner ( System . in );
        public static void main ( String [] args ) {
                showMenu ();
                // gotoLogin();
        }
        public static void showMenu (){ // 递归没有出口,将导致栈内存溢出
                showMenu ();
        }
        public static void gotoLogin (){ // 间接递归
                System . out . println ( " 登录 " );
                System . out . println ( " 请输入菜单编号: " );
                int number = sc . nextInt ();
                if ( number == 1 ){
                        gotoMain ();
                } else {
                        System . out . println ( " 感谢使用 XXX 系统 " );
                }
        }
        public static void gotoMain (){ // 间接递归
                System . out . println ( " 主菜单 " );
                System . out . println ( " 请输入菜单编号: " );
                int number = sc . nextInt ();
                if ( number == 5 ){
                        gotoLogin ();
                } else {
                        System . out . println ( " 你选择了其他菜单 " );
                }
        }
}
示例
1.使用递归求1~100的累加和。
package com . we . file ;
/**
* 使用递归求 1~100 的累加和。
*/
public class Example6 {
        public static void main ( String [] args ) {
                int result = sum ( 100 );
                System . out . println ( result );
        }
        public static int sum ( int number ){
                if ( number == 1 ) return 1 ;
                return number + sum ( number - 1 );
        }
}
2.使用递归打印文件夹下所有文件信息
// 递归遍历文件夹
public static void recursiveFolder ( File folder ){
        if ( folder . isDirectory ()){ // 检测是否是文件夹
                File [] files = folder . listFiles ();
                for ( File file : files ){
                        if ( file . isDirectory ()){ // 如果是文件夹,就再调用方法进行查看
                                recursiveFolder ( file );
                        } else {
                                System . out . println ( file . getPath ());
                        }
                }
        } else { // 不是文件夹就直接打印文件的路径
                        System . out . println ( folder . getPath ());
        }
}

练习

使用递归求 6 的阶乘。
public static int multiply ( int number ){
        if ( number == 0 || number == 1 ) return 1 ;
        return number * multiply ( number - 1 );
}

思考:如何删除一个文件夹?

public static void deleteFolder ( File folder ){
        if ( folder . isDirectory ()){ // 是文件夹就需要再进去看
                File [] files = folder . listFiles ();
                if ( files != null ){
                        for ( File file : files ){
                                if ( file . isDirectory ()){
                                        deleteFolder ( file );
                                } else {
                                        file . delete ();
                                }
                        }
                        folder . delete (); // 文件夹中文件删除完毕之后,文件夹也需要删除掉
                }
        } else { // 不是文件夹,直接删除
                folder . delete ();
        }
}

Java SE文章参考:Java SE入门及基础知识合集-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/746472.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

《Effective Modern C++》- 极精简版 36-42条

本文章属于专栏《业界Cpp进阶建议整理》 继续上篇《Effective Modern C》- 极精简版 30-35条。 本文列出《Effective Modern C》的36-42条的个人理解的极精简版本。 Item36、如果有异步的&#xff0c;请指定std::launch::async demo代码为&#xff1a; int calculateSum(int a…

MySQL 数据库压力测试

文章目录 前言1. 安装部署1.1 二进制安装1.2 源码安装 2. 服务器性能测试2.1 CPU2.2 内存2.3 磁盘 3. MySQL 基准测试3.1 参数解析3.2 压测命令3.3 输出解读3.4 结果分析 前言 Sysbench 是一个开源的多线程基准测试工具&#xff0c;也是目前使用最多的 MySQL 压力测试工具。本…

树莓派与电脑视频实时传输实现

编程环境 1、 树莓派 4B 2、 windows 编程语言 python 应用 tkinter scoket opencv 效果 视频同传 服务端视频初始化 服务端视频读取 windows 客户端接收视频流&#xff0c;队列存储 解析视频&#xff0c;存入队列 ui页面数据刷新 下载链接&#xff1a;https://…

什么是虚假唤醒?为什么会产生虚假唤醒?

什么是虚假唤醒&#xff1f; 当一定的条件触发时会唤醒很多在阻塞态的线程&#xff0c;但只有部分的线程唤醒是有用的&#xff0c;其余线程的唤醒是多余的。 比如说卖货&#xff0c;如果本来没有货物&#xff0c;突然进了一件货物&#xff0c;这时所有的顾客都被通知了&#x…

1178: 密码翻译(python)

题目描述 在情报传递过程中&#xff0c;为了防止情报被截获&#xff0c;往往需要对情报用一定的方式加密&#xff0c;简单的加密算法虽然不足以完全避免情报被破译&#xff0c;但仍然能防止情报被轻易的识别。我们给出一种最简的的加密方法&#xff0c;对给定的一个字符串&…

elasticsearch篇:数据聚合

1.数据聚合 聚合&#xff08;aggregations&#xff09;可以让我们极其方便的实现对数据的统计、分析、运算。例如&#xff1a; 什么品牌的手机最受欢迎&#xff1f; 这些手机的平均价格、最高价格、最低价格&#xff1f; 这些手机每月的销售情况如何&#xff1f; 实现这些…

VUE3项目学习系列--Axios二次封装(五)

Axios中文文档 | Axios中文网 (axios-http.cn) Axios 是一个基于 promise 网络请求库&#xff0c;作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequ…

【洛谷 P8637】[蓝桥杯 2016 省 B] 交换瓶子 题解(贪心算法)

[蓝桥杯 2016 省 B] 交换瓶子 题目描述 有 N N N 个瓶子&#xff0c;编号 1 ∼ N 1 \sim N 1∼N&#xff0c;放在架子上。 比如有 5 5 5 个瓶子&#xff1a; 2 , 1 , 3 , 5 , 4 2,1,3,5,4 2,1,3,5,4 要求每次拿起 2 2 2 个瓶子&#xff0c;交换它们的位置。 经过若干次…

解释器模式(Interpreter Pattern)

解释器模式 说明 解释器模式&#xff08;Interpreter Pattern&#xff09;属于行为型模式&#xff0c;是指给定一门语言&#xff0c;定义它的语法&#xff08;文法&#xff09;的一种表示&#xff0c;并定义一个解释器&#xff0c;该解释器使用该表示来解释语言中的句子。是一…

[NSSRound#18 Basic]web解析

文章目录 门酱想玩什么呢&#xff1f;Becomeroot 门酱想玩什么呢&#xff1f; 打开题目&#xff0c;加载完视频后要求我们给个游戏链接 点开评论区不难发现应该是想玩元梦之星&#xff0c;这里有个评论功能可以上传图片 我们随便输入点东西发现是插入并赋值到content元素里面 …

提示找不到MSVCP140.dll无法继续执行此代码的多种解决方法

当计算机系统在运行过程中突然提示“丢失MSVCP140.dll”这一错误信息时&#xff0c;意味着系统无法找到并加载这个至关重要的动态链接库文件。MSVCP140.dll是Microsoft Visual C Redistributable Package的一部分&#xff0c;对于许多基于Windows的应用程序来说&#xff0c;尤其…

Exam in MAC [容斥]

题意 思路 正难则反 反过来需要考虑的是&#xff1a; (1) 所有满条件一的(x,y)有多少对&#xff1a; x 0 时&#xff0c;有c1对 x 1 时&#xff0c;有c对 ...... x c 时&#xff0c;有1对 以此类推 一共有 (c2)(c1)/2 对 (2) 符合 x y ∈ S的有多少对&#xff1a…

openssl3.2 - note - Getting Started with OpenSSL

文章目录 openssl3.2 - note - Getting Started with OpenSSL概述笔记openssl 历史版本Configure 选项开关支持的OSopenssl 文档简介安装新闻每个平台的安装文档支持的命令列表配置文件格式环境变量 END openssl3.2 - note - Getting Started with OpenSSL 概述 看到官方文档…

物联网技术助力智慧城市转型升级:智能、高效、可持续

目录 一、物联网技术概述及其在智慧城市中的应用 二、物联网技术助力智慧城市转型升级的路径 1、提升城市基础设施智能化水平 2、推动公共服务智能化升级 3、促进城市治理现代化 三、物联网技术助力智慧城市转型升级的成效与展望 1、成效显著 2、展望未来 四、物联网技…

Java中文乱码问题解析与解决方案

在日常工作中&#xff0c;我们经常会遇到中文乱码的问题。乱码问题不仅影响用户体验&#xff0c;还可能导致数据丢失或解析错误。因此&#xff0c;了解和掌握中文乱码问题的原因和解决方案&#xff0c;对于Java开发者来说至关重要。本文将分析常见的Java中文乱码场景&#xff0…

Python chardet.detect 字符编码检测

chardet.detect 是 Python 的一个库&#xff0c;用于检测给定字节串的字符编码。其检测原理基于统计学方法。 具体来说&#xff0c;chardet.detect 使用了一种叫做统计字符 n-gram&#xff08;通常为 n1 或 n2&#xff09;的方法。它会统计字节串中每个字符或字符对出现的频率…

【C++初阶】C++入门(上)

C的认识 ①什么是C&#xff1f; ​ C语言是结构化和模块化的语言&#xff0c;适合处理较小规模的程序。对于复杂的问题&#xff0c;规模较大的程序&#xff0c;需要高度的抽象和建模时&#xff0c;C语言则不合适。 ​ 于是1982年&#xff0c;Bjarne Stroustrup&#xff08;本…

D-阿洛酮糖-DAEase酶固定化载体及混合糖液分离

#D-阿洛酮糖-DAEase酶固定化载体及混合糖液分离 ​阿洛酮糖为白色固体晶体&#xff0c;无气味&#xff0c;具有较大的溶解度&#xff0c;柔和的口感&#xff0c;其具有传统甜味剂蔗糖70%的甜度&#xff0c;却几乎不提供任何热量。其与食物中的蛋白质&#xff0c;如鸡蛋蛋白发生…

ntp 部署

文章目录 简介ntp和ntpdate区别环境准备启动 简介 ntp全名 network time protocol 。NTP服务器可以为其他主机提供时间校对服务 ntp和ntpdate区别 两个服务都是centos自带的&#xff08;centos7中不自带ntp&#xff09;。ntp的安装包名是ntp&#xff1b;ntpdate的安装包是ntp…

【leetcode+深度/广度优先搜索】841. 钥匙和房间 (DFS,BFS)

leetcode-cn&#xff1a;leetcode面试75道精华&#xff1a;https://leetcode.cn/studyplan/leetcode-75/ 841.钥匙和房间&#xff1a;https://leetcode.cn/problems/keys-and-rooms/description/ 一、题目&#xff1a;841. 钥匙和房间 有 n 个房间&#xff0c;房间按从 0 到 n…