【JavaEE】IO基础知识及代码演示

目录

一、File

1.1 观察get系列特点差异

1.2 创建文件

1.3.1 delete()删除文件

1.3.2 deleteOnExit()删除文件

1.4 mkdir 与 mkdirs的区别

1.5 文件重命名

二、文件内容的读写----数据流

1.1 InputStream

1.1.1 使用 read() 读取文件

1.2 OutputStream

1.3 代码演示

        1.3.1 扫描指定⽬录,并找到名称中包含指定字符的所有普通⽂件(不包含⽬录),并且后续询问⽤⼾是否 要删除该⽂件

        1.3.2 进⾏普通⽂件的复制

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


一、File

        (1)属性

        (2)构造方法

在Windows操作平台上,通常使用第二种构造方法

        (3)方法

1.1 观察get系列特点差异
import java.io.File;
import java.io.IOException;
public class Demo4 {public static void main(String[] args) throws IOException {File file = new File("C:./test");System.out.println(file.getName());//文件名字System.out.println(file.getParent());//父目录文件路径System.out.println(file.getPath());//文件路径System.out.println(file.getAbsolutePath());//绝对路径System.out.println(file.getCanonicalPath());//修饰过的绝对路径}
}

        由于在 Java 中 “\” 有转义字符 的功能,所以我们输入路径的时候需要多加一个“\”。上面演示了五种方法。

1.2 创建文件
public class Demo5 {public static void main(String[] args) throws IOException {File file = new File("./test");boolean ok = file.isFile();System.out.println(ok);file.createNewFile();boolean ok1 = file.isFile();System.out.println(ok1);}
}

1.3.1 delete()删除文件
public class Demo5 {public static void main(String[] args) throws IOException {File file = new File("./test");file.createNewFile();boolean ok = file.isFile();System.out.println(ok);file.delete();boolean ok2 = file.isFile();System.out.println(ok2);}
}

可以见到,基础的操作并不难,我们可以通过file.createNewFile()来创建新文件,也可以通过file.delete()来删除文件。

1.3.2 deleteOnExit()删除文件
public class Demo5 {public static void main(String[] args) throws IOException {File file = new File("./test");file.createNewFile();boolean ok = file.isFile();System.out.println(ok);file.deleteOnExit();System.out.println("删除完成");System.out.println(file.exists());Scanner scanner = new Scanner(System.in);scanner.next();}
}

可以看到我们掉用户 scanner 函数阻塞进程,掉用 deleteOnExit() 之后,文件并没有立即删除,只有当我们结束进程的之后才能删除。

1.4 mkdir 与 mkdirs的区别

       

import java.io.File;
import java.io.IOException;
public class Demo6 {public static void main(String[] args) throws IOException {File dir = new File("some-parent\\some-dir"); // some-parent 和 soSystem.out.println(dir.isDirectory());System.out.println(dir.isFile());System.out.println(dir.mkdir());System.out.println(dir.isDirectory());System.out.println(dir.isFile());}}

import java.io.File;
import java.io.IOException;public class Demo7 {public static void main(String[] args) throws IOException {File dir = new File("some-parent\\some-dir"); // some-parent 和 soSystem.out.println(dir.isDirectory());System.out.println(dir.isFile());System.out.println(dir.mkdirs());System.out.println(dir.isDirectory());System.out.println(dir.isFile());System.out.println(dir.getAbsolutePath());}}

由此可见,mkdirs对比与mkdir来说,mkdirs可以创建中间不存在的目录。

1.5 文件重命名
import java.io.File;
import java.io.IOException;public class Demo8 {public static void main(String[] args) throws IOException {File file = new File("./some-parent");File dest = new File("./some-dir");System.out.println(file.getCanonicalPath());System.out.println(dest.exists());System.out.println(file.renameTo(dest));System.out.println(dest.getCanonicalPath());System.out.println(dest.exists());}
}

import java.io.File;
import java.io.IOException;public class Demo8 {public static void main(String[] args) throws IOException {File file = new File("./some-parent/some-dir");File dest = new File("./some-dir");System.out.println(file.getCanonicalPath());System.out.println(dest.exists());System.out.println(file.renameTo(dest));System.out.println(dest.getCanonicalPath());System.out.println(dest.exists());}
}

可以看到,文件重命名也可以浅显的理解为,文件路径移动

二、文件内容的读写----数据流

上述我们只学会了 操作文件 ,对于操作文件内容,我们则需要用到数据流相关知识。Reader读取出来的是char数组或者String ,InputStream读取出来的是byte数组。

1.1 InputStream

InputStream 只是⼀个抽象类,要使⽤还需要具体的实现类。关于 InputStream 的实现类有很多,对于文件的读写 ,我们只需要关心 FIleInputStream,FileInputStream()里可以是 文件路径 或者 文件,下面是两种输出方式的演示。

1.1.1 使用 read() 读取文件
public class Demo9 {public static void main(String[] args) {try(InputStream inputStream = new FileInputStream("./test.txt")){while(true){int n = inputStream.read();if(n == -1){break;}System.out.printf("%c",n);}}catch (IOException e){e.printStackTrace();}}
}
public class Demo10 {public static void main(String[] args) {try(InputStream inputStream = new FileInputStream("./test.txt")){byte[] bytes = new byte[21024];while (true){int n = inputStream.read(bytes);if(n == -1){break;}for (int i = 0; i <n ; i++) {System.out.printf("%c",bytes[i]);}}}catch(IOException e){e.printStackTrace();}}
}

将⽂件完全读完的两种⽅式。相⽐较⽽⾔,后⼀种的 IO 次数更少,性能更好

1.2 OutputStream

OutputStream 同样只是⼀个抽象类,要使⽤还需要具体的实现类。对于文件的读写,我们只需要关注FileOutputStream,下面是两种输入方式的演示。

public class Demo11 {public static void main(String[] args) {try(OutputStream os = new FileOutputStream("./output.txt",true)){os.write('h');os.write('e');os.write('l');os.write('l');os.write('o');os.flush();}catch(IOException e){e.printStackTrace();}}
}
public class Demo12 {public static void main(String[] args) {try(OutputStream os = new FileOutputStream("./output.txt")){byte[] buf = new byte[]{(byte) 'h',(byte) 'e',(byte) 'l',(byte) 'l',(byte) 'o'};os.write(buf);os.flush();}catch(IOException e){e.printStackTrace();}}
}
1.3 代码演示
        1.3.1 扫描指定⽬录,并找到名称中包含指定字符的所有普通⽂件(不包含⽬录),并且后续询问⽤⼾是否 要删除该⽂件
mport java.io.File;
import java.util.Scanner;public class Demo14 {public static void main(String[] args) {System.out.println("请输入想扫描的文件");System.out.println("->");Scanner scanner = new Scanner(System.in);String rootPath = scanner.next();File file = new File(rootPath);System.out.println("请输入想删除的文件名字");;System.out.println("->");String key = scanner.next();scan(file,key);}private static void scan(File file, String key) {if(!file.isDirectory()){System.out.println("输入的路径有误!");return;}File[] files = file.listFiles();for (File f : files){if(f.isFile()){if(f.getName().contains(key)){doDelete(f,key);}}else {scan(f,key);}}}private static void doDelete(File f,String k) {System.out.println(f.getAbsolutePath()+"是否删除  Y/N");Scanner scanner = new Scanner(System.in);String key = scanner.next();if(key.equals("Y")||key.equals("y")){f.delete();}}
}
        1.3.2 进⾏普通⽂件的复制
import java.io.*;
import java.util.Scanner;public class Demo13 {public static void main(String[] args) throws IOException {System.out.println("请输入想复制的路径");System.out.print("->");Scanner scanner = new Scanner(System.in);String rootPath = scanner.next();System.out.println("请输入复制后的路径");System.out.print("->");String scrPath = scanner.next();try(InputStream inputStream = new FileInputStream(rootPath);OutputStream outputStream = new FileOutputStream(scrPath)){byte[] buf = new byte[1024];while(true){int n = inputStream.read(buf);if(n == -1){break;}outputStream.write(buf);}}catch (IOException e) {e.printStackTrace();}}
}

        1.3.3 扫描指定⽬录,并找到名称或者内容中包含指定字符的所有普通⽂件(不包含⽬录)
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;public class Demo3 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入想查询的路径");System.out.print("->");String rootPath = scanner.next();File rootFile = new File(rootPath);if(!rootFile.isDirectory()){System.out.println("输入的文件路径有误!");return;}System.out.println("请输入想查询的 关键字");System.out.print("->");String key = scanner.next();scan(rootFile,key);}private static void scan(File rootFile, String key) {if(!rootFile.isDirectory()){return;}File[] files = rootFile.listFiles();if(files == null|| files.length == 0){return;}for (File f : files){if(f.isFile()){doSearch(f,key);}else {scan(f,key);}}}private static void doSearch(File f, String key) {StringBuilder sb = new StringBuilder();try(Reader reader = new FileReader(f)){char[] chars = new char[1024];while(true){int n = reader.read(chars);if(n == -1){break;}String s = new String(chars,0,n);sb.append(s);}}catch(IOException e){e.printStackTrace();}if(sb.indexOf(key) == -1){return;}System.out.println("找到目标文件" + f.getAbsolutePath());}
}

=========================================================================

最后如果感觉对你有帮助的话,不如给博主来个三连,博主会继续加油的ヾ(◍°∇°◍)ノ゙

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

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【LLM多模态】文生视频评测基准VBench

note VBench的16个维度自动化评估指标代码实践&#xff08;待完成&#xff09;16个维度的prompt举例人类偏好标注&#xff1a;计算VBench评估结果与人类偏好之间的相关性、用于DPO微调 文章目录 note一、相关背景二、VBench评测基准概述&#xff1a;论文如何解决这个问题&…

yum install时候报错

报错 Another app is currently holding the yum lock; waiting for it to exit 另外一个yum命令完成了死锁大概率是因为执行yum 命令的时候报错&#xff0c;然后强制退出了 解决方法 找到进程杀死进程 ps aux | grep yum这个进程号&#xff1a;你在上述命令和报错中都看的进程…

ubuntu20.04下载cuda11.8

nvidia官方地址&#xff1a;https://developer.nvidia.com/cuda-downloads wget https://developer.download.nvidia.com/compute/cuda/11.8.0/local_installers/cuda_11.8.0_520.61.05_linux.run输入该命令后 sudo sh cuda_11.8.0_520.61.05_linux.run gedit ~/.bashrcexport…

9. Transforms的使用(四)--Compose

Transforms的使用&#xff08;四&#xff09; 1. 为什么要使用Compose类 在深度学习模型的训练过程中&#xff0c;往往需要对图像按顺序进行一系列的变化&#xff0c;如果把系列变化按顺序写成代码会比较冗余Compose实现了将所有的系列变化进行集合的操作&#xff0c;从代码层…

【智路】智路OS air-edge 开发者手册 功能概述

功能概述 https://airos-edge.readthedocs.io/zh/latest/airospkg/airospkg.html 智路OS包支持部署在智路OS开源版本和智路OS发行版。 智路OS发行版&#xff08;airos distribution&#xff09;是基于智路OS的商业化版本。包括智路OS内核层、系统工具、库、软件包管理系统等…

【裸机装机系列】6.kali(ubuntu)-图形界面优化-让linux更适合你的使用习惯

接下来就是图形化界面操作的部分了。会用少量截图来说明&#xff0c;图太多会影响阅读体验&#xff0c;直接文字来描述过程吧。 1> 入口 任务栏左上角——> 开始菜单——> settings——> settings manager 大部分配置都会在这里面设置。 2> 设置里面分的4大…

CS61C 2020计算机组成原理Lab01-数字表示,溢出

1. Exercise 1 :See what you can C # 用gcc 来编译可执行文件如program.c gcc program.c # 就可以得到一个executable file named a.out. ./a.out# 如果想给这个可执行文件命名&#xff0c;则使用 -o gcc -o program program.c ./program# 使用-g 能得到一个 可执行程序的deb…

ElementUI 布局——行与列的灵活运用

ElementUI 布局——行与列的灵活运用 一 . 使用 Layout 组件1.1 注册路由1.2 使用 Layout 组件 二 . 行属性2.1 栅格的间隔2.2 自定义元素标签 三 . 列属性3.1 列的偏移3.2 列的移动 在现代网页设计中&#xff0c;布局是构建用户界面的基石。Element UI 框架通过其强大的 <e…

计算架构模式之接口高可用

接口高可用整体框架 接口高可用主要应对两类问题&#xff1a;雪崩效应和链式效应。 雪崩&#xff1a;当请求量超过系统处理能力之后&#xff0c;会导致系统性能螺旋快速下降&#xff0c;本来系统可以处理1000条&#xff0c;但是当请求量超过1200的时候&#xff0c;此时性能会下…

深入理解算法效率:时间复杂度与空间复杂度

目录 引言 一、算法效率的基础 二、时间复杂度 1.概念 2.常见类型 1.O(1) — 常数阶 2.O(n) — 线性阶 3.O(n^2) — 平方阶 4.O(2^&#x1d45b;) — 指数阶 5.O(log &#x1d45b;) — 对数阶 3.总结 三、空间复杂度 1.概念 2.常见类型 1.O(1) — 常数阶 2.…

为你的 Github 仓库引入自动构建的Github Pages静态页面

1. 设置config文件 在Github仓库根目录下创建_config.yml文件。其中的内容为&#xff1a; plugins:- jekyll-relative-links relative_links:enabled: truecollections: true include:- CONTRIBUTING.md- README.md- LICENSE.md- COPYING.md- CODE_OF_CONDUCT.md- CONTRIBUTI…

性能小白终于能看懂Jmeter报告了

对于刚接触性能测试的初学者来说&#xff0c;分析JMeter生成的测试报告无疑是一个巨大的挑战。面对大量的数据信息&#xff0c;如何快速理解响应时间、吞吐量、错误率等关键指标&#xff0c;往往让人感到困惑。今天&#xff0c;让我们一起探讨如何轻松看懂JMeter的性能测试报告…

沉浸式体验和评测Meta最新超级大语言模型405B

2024年7月23日&#xff0c; 亚马逊云科技的AI模型托管平台Amazon Bedrock正式上线了Meta推出的超级参数量大语言模型 - Llama 3.1模型&#xff0c;小李哥也迫不及待去体验和试用了该模型&#xff0c;那这么多参数量的AI模型究竟强在哪里呢&#xff1f;Llama 3.1模型是Meta&…

nodejs 007:错误npm error Error: EPERM: operation not permitted, symlink

完整错误信息 npm error Error: EPERM: operation not permitted, symlink npm warn cleanup Failed to remove some directories [ npm warn cleanup [ npm warn cleanup C:\\Users\\kingchuxing\\Documents\\IPFS\\orbit-db-set-master\\node_modules\\ipfs-cli, npm…

C++11 回调函数

【C引用进阶】C11 回调函数 文章目录 【C引用进阶】C11 回调函数 回调函数的实现往往是应用层&#xff08;更上层&#xff09;的程序拥有&#xff0c;而调用者是底层的程序。 相当于说&#xff0c;底层的程序是一个服务员&#xff0c;应用层程序是客人&#xff0c;客人需要客房…

天融信把桌面explorer.exe删了,导致开机之后无windows桌面,只能看到鼠标解决方法

win10开机进入桌面&#xff0c;发现桌面无了&#xff0c;但是可以ctrlaltdelete调出任务管理器 用管理员权限打开cmd&#xff0c;输入&#xff1a; sfc /scanfilec:\windowslexplorer.exe 在运行C:\windows\Explorer.exe&#xff1b;可以进入桌面&#xff0c;但是隔离几秒钟…

VMamba: Visual State Space Model 论文总结

题目&#xff1a;VMamba: Visual State Space Model&#xff08;视觉状态空间模型&#xff09; 论文&#xff1a;[2401.10166] VMamba: Visual State Space Model (arxiv.org) 源码&#xff1a;https://arxiv.org/pdf/2401.10166 (github.com) 目录 一、摘要 二、引言 三、方…

【JS|第27期】网页文件传输:Blob与Base64的对决

日期&#xff1a;2024年9月12日 作者&#xff1a;Commas 签名&#xff1a;(ง •_•)ง 积跬步以致千里,积小流以成江海…… 注释&#xff1a;如果您觉得有所帮助&#xff0c;帮忙点个赞&#xff0c;也可以关注我&#xff0c;我们一起成长&#xff1b;如果有不对的地方&#xf…

keil 中 printf重定向

int fputc(int ch, FILE *f) {HAL_UART_Transmit(&huart1, (void*)&ch, 1, 1000);return ch;} 同时勾选&#xff0c;使用微库

1.使用 VSCode 过程中的英语积累 - File 菜单(每一次重点积累 5 个单词)

前言 学习可以不局限于传统的书籍和课堂&#xff0c;各种生活的元素也都可以做为我们的学习对象&#xff0c;本文将利用 VSCode 页面上的各种英文元素来做英语的积累&#xff0c;如此做有 3 大利 这些软件在我们工作中是时时刻刻接触的&#xff0c;借此做英语积累再合适不过&a…