Java中常见的文件操作

news/2025/2/22 19:32:58/

作者:~小明学编程 

文章专栏:JavaEE

格言:热爱编程的,终将被编程所厚爱。
在这里插入图片描述

目录

操作文件

File类

属性

构造方法

常见方法

重要方法的操作演示

文件内容的读写

FileInputStream

OutputStream

按照字符读入

按照字符写入

实战用法


操作文件

Java 中通过 java.io.File 类来对一个文件(包括目录)进行抽象的描述。注意,有 File 对象,并不
代表真实存在该文件。

File类

属性

修饰符及类型属性说明
static StringpathSeparator依赖于系统的路径分隔符,String 类型的表示
static charpathSeparator依赖于系统的路径分隔符,char 类型的表示

构造方法

签名说明
File(File parent, String
child)
根据父目录 + 孩子文件路径,创建一个新的 File 实例
File(String pathname)根据文件路径创建一个新的 File 实例,路径可以是绝对路径或者
相对路径
File(String parent, String
child)
根据父目录 + 孩子文件路径,创建一个新的 File 实例,父目录用
路径表示

常见方法

修饰符及返回
值类型
方法签名说明
StringgetParent()返回 File 对象的父目录文件路径
StringgetName()返回 FIle 对象的纯文件名称
StringgetPath()返回 File 对象的文件路径
StringgetAbsolutePath()返回 File 对象的绝对路径
StringgetCanonicalPath()返回 File 对象的修饰过的绝对路径
booleanexists()判断 File 对象描述的文件是否真实存在
booleanisDirectory()判断 File 对象代表的文件是否是一个目录
booleanisFile()判断 File 对象代表的文件是否是一个普通文件
booleancreateNewFile()根据 File 对象,自动创建一个空文件。成功创建后返
回 true
booleandelete()根据 File 对象,删除该文件。成功删除后返回 true
voiddeleteOnExit()根据 File 对象,标注文件将被删除,删除动作会到
JVM 运行结束时才会进行
String[]list()返回 File 对象代表的目录下的所有文件名
File[]listFiles()返回 File 对象代表的目录下的所有文件,以 File 对象
表示
booleanmkdir()创建 File 对象代表的目录
booleanmkdirs()创建 File 对象代表的目录,如果必要,会创建中间目
booleanrenameTo(File
dest)
进行文件改名,也可以视为我们平时的剪切、粘贴操
booleancanRead()判断用户是否对文件有可读权限
booleancanWrite()判断用户是否对文件有可写权限

重要方法的操作演示

    public static void main(String[] args) throws IOException {File file = new File("D:\\.11111\\Demo");System.out.println(file.getParent());//获取父目录的文件名称System.out.println(file.getName());//获取文件名System.out.println(file.getPath());//获取到文件的路径System.out.println(file.getAbsoluteFile());//返回 File 对象的绝对路径System.out.println(file.getCanonicalPath());//返回 File 对象的修饰过的绝对路径File file1 = new File("./demo.txt");//输入一个基准路径System.out.println(file1.getParent());//获取父目录的文件名称System.out.println(file1.getName());//获取文件名System.out.println(file1.getPath());//获取到文件的路径(构造方法中的路径)System.out.println(file1.getAbsoluteFile());//在基准路径的基础上把相对路径给拼接上去System.out.println(file1.getCanonicalPath());//返回 File 对象的修饰过的绝对路径}

首先给大家介绍的就是绝对路径和相对路径,绝对路径就是我们常见的D:\.1学习资料\JavaEE初阶

这种写法,而相对路径就是./test.txt  的这种写法其中的点就是我们当前所在的路径。

这是上述代码的打印结果,值得注意的是 getAbsoluteFile()是对我们相对路径和基准路径的一个拼接,而getCanonicalPath()是直接打印这个完整的路径。

    public static void main(String[] args) {File file = new File("D:\\.11111\\Demo");System.out.println(file.exists());//判断对象描述的文件是否存在System.out.println(file.isDirectory());//判断对象描述的是否是一个目录System.out.println(file.isFile());//判断当前是否是一个普通的文件}

    public static void main(String[] args) throws IOException {File file = new File("./test.txt");System.out.println(file.exists());System.out.println("创建文件");file.createNewFile();//创建文件System.out.println(file.exists());}

    public static void main(String[] args) {File file = new File("./test.txt");System.out.println(file.exists());//truefile.delete();//删除文件System.out.println(file.exists());//false}
    public static void main(String[] args) {File file = new File("./aaa/bbb/ccc/ddd");file.mkdirs();//创建多级目录}public static void main1(String[] args) {File file = new File("./aaa");file.mkdir();//创建该目录System.out.println(file.isDirectory());}
    public static void main(String[] args) {File file = new File("./");System.out.println(Arrays.toString(file.list()));//返回当前目录下的所有文件System.out.println(Arrays.toString(file.listFiles()));//返回当前目录下的所有文件,以file对象表示}
    public static void main(String[] args) {File file = new File("./aaa");File file1 = new File("./www");file.renameTo(file1);//更改当前目录的名字}

文件内容的读写

FileInputStream

常用方法

修饰符及
返回值类
方法签名说明
intread()读取一个字节的数据,返回 -1 代表已经完全读完了
intread(byte[] b)最多读取 b.length 字节的数据到 b 中,返回实际读到的数
量;-1 代表以及读完了
intread(byte[] b,
int off, int len)
最多读取 len - off 字节的数据到 b 中,放在从 off 开始,返
回实际读到的数量;-1 代表以及读完了
voidclose()关闭字节流
    public static void main(String[] args){//构造方法里面的路径可以是绝对路径也可以是相对路径InputStream input = null;try {input = new FileInputStream("D:\\.11111\\Demo\\as.txt");int b = 0;while (b!=-1) {b = input.read();System.out.println(b);}input.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {input.close();} catch (IOException e) {e.printStackTrace();}}}

这里要注意我们的回收资源,但是这种写法有些的繁琐,所以我们就有了下面的这种写法。

    public static void main(String[] args) {try (InputStream input = new FileInputStream("D:\\.11111\\Demo\\as.txt")){//自动回收int b = 0;while (b!=-1) {b = input.read();System.out.println(b);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

我们在try里面把对象就给构造出来,这样就不用我们再去回收资源了,但是这种写法要保证我们当前的类是实现了Closeable接口的。

    public static void main3(String[] args) {try(InputStream inputStream = new FileInputStream("D:\\.11111\\Demo\\as.txt")) {while (true) {byte[] bytes = new byte[1024];int len = inputStream.read(bytes);//返回的是读到的长度if (len==-1) {break;}for (int i = 0; i < len; i++) {System.out.println(bytes[i]);}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

我们也可以一次性读多个字节然后把读到的字节放到数组里面去。

OutputStream

修饰
符及
返回
值类
方法签名说明
voidwrite(int b)写入要给字节的数据
voidwrite(byte[]
b)
将 b 这个字符数组中的数据全部写入 os 中
intwrite(byte[]
b, int off,
int len)
将 b 这个字符数组中从 off 开始的数据写入 os 中,一共写 len 个
voidclose()关闭字节流
voidflush()重要:我们知道 I/O 的速度是很慢的,所以,大多的 OutputStream 为
了减少设备操作的次数,在写数据的时候都会将数据先暂时写入内存的
一个指定区域里,直到该区域满了或者其他指定条件时才真正将数据写
入设备中,这个区域一般称为缓冲区。但造成一个结果,就是我们写的
数据,很可能会遗留一部分在缓冲区中。需要在最后或者合适的位置,
调用 flush(刷新)操作,将数据刷到设备中
    public static void main2(String[] args) {//按照字节来写文件try(OutputStream out = new FileOutputStream("D:\\.11111\\Demo\\as.txt")){out.write(97);out.write(98);out.write(99);out.write(100);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

按照字符读入

    public static void main1(String[] args) {try(Reader reader = new FileReader("D:\\.11111\\Demo\\as.txt")){//按照字符来读文件while (true) {char[] buffer = new char[1024];int len = reader.read(buffer);if (len==-1) {break;}
//            for (int i = 0; i < len; i++) {
//                System.out.println(buffer[i]);
//            }String str = new String(buffer,0,len);System.out.println(str);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

按照字符写入

    //按照字符来写文件public static void main(String[] args) {try(Writer writer = new FileWriter("D:\\.11111\\Demo\\as.txt")){writer.write("qweq");} catch (IOException e) {e.printStackTrace();}}

实战用法

扫描指定目录,并找到名称中包含指定字符的所有普通文件(不包含目录),并且后续询问用户是否要删除该文件。

    //删除文件的操作public static void main(String[] args) throws IOException {Scanner scanner = new Scanner(System.in);System.out.println("请输入你要删除文件所存在的根路径");String root = scanner.next();System.out.println("请输入想要删除的文件名");String name = scanner.next();File file = new File(root);//如果当前文件不是目录if (!file.isDirectory()){System.out.println("您所输入的文件路径有误");}scannerDir(file,name);}private static void scannerDir(File root, String name) throws IOException {File[] files = root.listFiles();if (files==null) {return;}for (File file:files) {if (file.isFile()) {if (file.getName().contains(name)) {deleteFile(file);}} else if (file.isDirectory()) {//如果当前的文件还是目录那就往下递归scannerDir(file,name);}}}private static void deleteFile(File file) throws IOException {System.out.println("是否确定要删除文件(Y/N):"+file.getCanonicalPath());Scanner scanner = new Scanner(System.in);String choice = scanner.next();if (choice.equals("Y")) {file.delete();System.out.println("文件删除成功");} else {System.out.println("删除失败");}}

进行普通文件的复制。

    public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入源文件的路径:");String src = scanner.next();System.out.println("请输入想要复制的文件所在的路径");String dest = scanner.next();File file = new File(src);if (!file.isFile()) {System.out.println("文件的路径不存在");}try(InputStream inputStream = new FileInputStream(src)) {try(OutputStream outputStream = new FileOutputStream(dest)){byte[] bytes = new byte[1024];int len = 0;while(true) {len = inputStream.read(bytes);if (len==-1) {break;}outputStream.write(bytes,0,len);System.out.println("复制完毕");}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

扫描指定目录,并找到名称或者内容中包含指定字符的所有普通文件(不包含目录)
 

    //查找指定字符串所在的路径public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入根路径:");String src = scanner.next();System.out.println("请输入想要查找的字符串:");String str = scanner.next();File file = new File(src);if (!file.isDirectory()) {System.out.println("当前所在的路径不存在");return;}scannerDir(file,str);}private static void scannerDir(File file, String str) {File[] files = file.listFiles();//列出当前的目录if (files==null) {return;}for (File file1:files) {if (file1.isFile()) {//查找当前文本if (containStr(file1,str)) {System.out.println(file1.getAbsoluteFile());}}else if (file.isDirectory()) {scannerDir(file1,str);}}}private static boolean containStr(File file1, String str) {StringBuilder stringBuilder = new StringBuilder();try(Reader reader = new FileReader(file1)) {char[] chars = new char[1024];while (true) {int len = reader.read(chars);if (len==-1) {break;}stringBuilder.append(chars,0,len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return stringBuilder.indexOf(str)!=-1;}

http://www.ppmy.cn/news/8036.html

相关文章

【华为OD机试真题2023 JAVA】相同数字的积木游戏1

华为OD机试真题,2023年度机试题库全覆盖,刷题指南点这里 相同数字的积木游戏1 知识点数组循环map 时间限制:1s 空间限制:256MB 限定语言:不限 题目描述: 小华和小薇一起通过玩积木游戏学习数学。 他们有很多积木,每个积木块上都有一个数字,积木块上的数字可能相同。 小…

hive 数据倾斜问题排查及 hive 优化

文章目录1.2 Explain 实例介绍1.3 Explain 总结2. Hive 建表优化2.1 创建分区表2.1.1 分区表基本操作2.1.2 二级分区2.1.3 动态分区2.2 合适的文件格式和压缩格式2.2.1 目前使用的存储格式3. HQL 语法优化3.1 列裁剪与分区裁剪3.2 Group by3.3 Count(Distinct) 去重统计3.4 Map…

【再学Tensorflow2】TensorFlow2的模型训练组件(2)

TensorFlow2的模型训练组件&#xff08;2&#xff09;损失函数损失函数和正则化项Tensorflow2内置的损失函数自定义损失函数评估指标常用的内置评估指标自定义评估指标优化器优化器的使用使用optimizer.apply_gradients使用optimizer.minimize使用model.fitTensorflow2内置的优…

前端devops——利用gitlab实现CI/CD自动化部署

目录 前言 一、前期准备 1、开启虚拟服务 2、下载并安装docker 二、开始部署 1、安装gitlab 2、修改默认账号登录密码 3、修改项目clone地址 三、Gitlab CI/CD 1、安装并运行gitlab-runner 2、执行runner 3、将项目注册到gitlab-runner 1、获取token 2、执行注册 …

基于springboot+Vue的宿舍管理系统前后端分离(程序+详细文档+数据库)

大家好✌&#xff01;我是CZ淡陌。一名专注以理论为基础实战为主的技术博主&#xff0c;将再这里为大家分享优质的实战项目&#xff0c;本人在Java毕业设计领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目&#xff0c;希望你能有所收获&#xff0c;少走一些弯路…

【自学Java】Java语言HelloWorld

Java语言HelloWorld详解 Java语言HelloWorld详解教程 我们使用 java 编辑器&#xff0c;新建一个 Helloworld.java 文件,输入如下内容&#xff1a; package com.haicoder;public class HelloWorld {public static void main(String[] args) {System.out.println("嗨客网…

app渗透为何一开启代理就断网?

前言 今天测试app&#xff0c;开启安卓代理&#xff0c;一点击准备登录时&#xff0c;抛出了如下提示“java.security.cert.CertPathValidatorException: Trust anchor for certification path not found”&#xff0c;大概意思就是证书的安全性问题 而当我把代理关闭了&#…

50+Vue经典面试题源码级详解,你值得收藏!(一天更新一题,持续更新!!!)

Vue经典面试题源码级详解1、Vue组件之间通信方式有哪些&#xff1f;分析&#xff1a;思路分析&#xff1a;回答范例&#xff1a;1. 组件通信常用方式有以下8种&#xff1a;2、根据组件之间关系讨论组件通信最为清晰有效2、v-if 和 v-for哪个优先级更高分析&#xff1a;思路分析…