当前位置: 首页 > news >正文

【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());}
}

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

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

相关文章:

【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 代码演示…...

安卓13系统导航方式分析以及安卓13修改默认方式为手势导航 android13修改导航方式

总纲 android13 rom 开发总纲说明 文章目录 1.前言2.问题分析3.代码分析4.代码修改5.彩蛋1.前言 系统导航方式默认一般是按键的,如果要改成手势的话,我们来看看用户怎么修改的: 设置=>系统=>手势=>系统导航,在这里进行修改。我们来分析下这个流程,并且将其修改为…...

[技术杂谈]暗影精灵8plus电竞版台式机安装和使用注意

最近买回二手台式机准备做深度学习训练模型使用。由于个人不是十分有钱&#xff0c;因此下血本入手一台&#xff0c;不然深度学习玩不转。配置&#xff1a;i9-12900K / 64G d4 3733频率 / 1TSSD2TB机械 / RTX3090 24G显卡 旗舰版 机箱45L超大机箱。买回来后整体不错&#…...

【加密算法基础——AES解密实践】

AES 解密实践 AES 解密是对使用 AES 加密算法加密的数据进行恢复的过程。 常用的解密方式有三种&#xff1a; 在线解密工具&#xff1a;格式比较好控制&#xff0c;但是有些在线工具兼容性不好&#xff0c;有时候无法解出&#xff0c;不知道是自己的密文密钥没找对&#xff0…...

Spring01

spring框架 spring是轻量级的容器框架 spring framework 1、Spring核心学习内容 IOC、AOp, jdbcTemplate,声明式事务 2、IOC:控制反转&#xff0c;孚以管理部8号对象 3.AOP:切面编程4.JDBCTemplate:是spring提供一套访问数据库的技术,应用性强&#xff0c;相对好理解5.声明式…...

gogps 利用广播星历解算卫星位置matlab函数satellite_orbits详细注解版

主要注释了广播星历计算GPS BDS卫星位置的。 function [satp, satv] satellite_orbits(t, Eph, sat, sbas)% SYNTAX: % [satp, satv] satellite_orbits(t, Eph, sat, sbas); % % INPUT: % t clock-corrected GPS time % Eph ephemeris matrix % sat satellite…...

Oracle按照某一字段值排序并显示,相同的显示序号

Oracle按照某一字段值排序并显示,相同的显示序号 最近的工作遇到对于相同的字段,按照序号去显示值,并对相同的值进行排序 实验了半天,感觉满意的答案,分享给大家 第一种: ROW_NUMBER 语法: ROW_NUMBER() OVER (ORDER BY your_column) AS sequence_number 说明: 根据your_column…...

【Java基础】String详解

文章目录 String一、String 概述1、基本特性2、不可变性3、String、StringBuilder、StringBuffer 二、字符串 创建与内存分配1、字面量 / 双引号2、new关键字3、StringBuilder.toString()4、intern() 方法5、小结 三、字符串 拼接1、常量常量2、变量 拼接3、final变量 拼接4、拼…...

cmd命令

常用命令 查看电脑名称&#xff1a; hostname 查看网卡信息&#xff1a; ipconfig 快速打开网络设置界面&#xff1a; control.exe netconnections 或 rundll32.exe shell32.dll,Control_RunDLL ncpa.cpld 打开防火墙设置&#xff1a; wf.msc 指定网卡设置IP地址&#…...

《中文Python穿云箭量化平台二次开发技术11》股票基本信息获取分析及应用示例【前十大股东占股比例提取及分析】

《中文Python穿云箭量化平台二次开发技术11》股票基本信息获取分析及应用示例【前十大股东占股比例提取及分析】 《中文Python穿云箭量化平台》是纯Python开发的量化平台&#xff0c;因此其中很多Python模块&#xff0c;我们可以自己设计新的量化工具&#xff0c;例如自己新的行…...

OSINT技术情报精选·2024年9月第1周

OSINT技术情报精选2024年9月第1周 2024.8.15版权声明&#xff1a;本文为博主chszs的原创文章&#xff0c;未经博主允许不得转载。 1、中国信通院&#xff1a;《大模型落地路线图研究报告(2024年)》 近年来&#xff0c;大模型技术能力不断创出新高&#xff0c;产业应用持续走…...

51单片机应用开发---二进制、十六进制与单片机寄存器之间的关系(跑马灯、流水灯实例)

实现目标 1、掌握二进制与十六进制之间的转换 2、掌握单片机寄存器与二进制、十六进制之间的转换 3、掌握单片机驱动跑马灯、流水灯的原理 一、二进制与十六进制之间的转换 1、二进制 二进制&#xff08;binary&#xff09;&#xff0c; 是在数学和数字电路中以2为基数的…...

信息安全工程师(6)网络信息安全现状与问题

一、网络信息安全现状 威胁日益多样化&#xff1a;网络攻击手段不断翻新&#xff0c;从传统的病毒、木马、蠕虫等恶意软件&#xff0c;到勒索软件、钓鱼攻击、DDoS攻击、供应链攻击等&#xff0c;威胁形式多种多样。这些攻击不仅针对个人用户&#xff0c;还广泛影响企业、政府等…...

亚数TrustAsia亮相第十四届智慧城市与智能经济博览会,入围“2024数据要素创新应用优秀成果”!

智博会 2024年9月6日至8日&#xff0c;由宁波市人民政府、浙江省经济和信息化厅、中国信息通信研究院、中国电子信息行业联合会、中国电信、中国移动、中国联通主办的2024世界数字经济大会暨第十四届智慧城市与智能经济博览会&#xff08;以下简称“智博会”&#xff09;在宁波…...

Linux基础开发环境(git的使用)

1.账号注册 git 只是一个工具&#xff0c;要想实现便捷的代码管理&#xff0c;就需要借助第三方平台进行操作&#xff0c;当然第三平台也是基于git 开发的 github 与 gitee 代码托管平台有很多&#xff0c;这里我们首选 Github &#xff0c;理由很简单&#xff0c;全球开发者…...

VS Code终端命令执行后老是出现 __vsc_prompt_cmd_original: command not found

VS Code终端命令执行后老是出现 __vsc_prompt_cmd_original: command not found。 如下图&#xff08;vscode终端中&#xff09;&#xff1a; 解决方案&#xff1a; 1、vim ~/.bashrc 2、在~/.bashrc里面加入命令&#xff1a;unset PROMPT_COMMAND 3、source ~/.bashrc...

春天(Spring Spring Boot)

基本概念 春天 Spring 是用于开发 Java 应用程序的开源框架&#xff0c;为解决企业应用开发的复杂性而创建。 Spring 的基本设计思想是利用 IOC&#xff08;依赖注入&#xff09;和 AOP &#xff08;面向切面&#xff09;解耦应用组件&#xff0c;降低应用程序各组件之间的耦…...

Oracle EBS AP预付款行分配行剩余预付金额数据修复

系统环境 RDBMS : 12.1.0.2.0 Oracle Applications : 12.2.6 问题情况 AP预付款已验证和自动审批但是未过账已经AP付款但是又撤消付款并且未过账问题症状 AP预付款暂挂: AP预付款行金额(等于发票金额)与分配行金额不相等: 取消AP预付款提示如下:...

【鸿蒙】HarmonyOS NEXT星河入门到实战7-ArkTS语法进阶

目录 1、Class类 1.1 Class类 实例属性 1.2 Class类 构造函数 1.3 Class类 定义方法 1.4 静态属性 和 静态方法 1.5 继承 extends 和 super 关键字 1.6 instanceof 检测是否实例 1.7.修饰符(readonly、private、protected 、public) 1.7.1 readonly 1.7.2 Private …...

Java设计模式—面向对象设计原则(六) ----->合成复用原则(CRP) (完整详解,附有代码+案例)

文章目录 3.6 合成复用原则(CRP)3.6.1 概述3.6.2 案列 3.6 合成复用原则(CRP) 合成复用原则(CRP)&#xff1a;Composite Reuse Principle&#xff0c;CRP 又叫&#xff1a; 组合/聚合复用原则&#xff08;Composition/Aggregate Reuse Principle&#xff0c;CARP&#xff09;…...

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…...

《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)

CSI-2 协议详细解析 (一&#xff09; 1. CSI-2层定义&#xff08;CSI-2 Layer Definitions&#xff09; 分层结构 &#xff1a;CSI-2协议分为6层&#xff1a; 物理层&#xff08;PHY Layer&#xff09; &#xff1a; 定义电气特性、时钟机制和传输介质&#xff08;导线&#…...

抖音增长新引擎:品融电商,一站式全案代运营领跑者

抖音增长新引擎&#xff1a;品融电商&#xff0c;一站式全案代运营领跑者 在抖音这个日活超7亿的流量汪洋中&#xff0c;品牌如何破浪前行&#xff1f;自建团队成本高、效果难控&#xff1b;碎片化运营又难成合力——这正是许多企业面临的增长困局。品融电商以「抖音全案代运营…...

VTK如何让部分单位不可见

最近遇到一个需求&#xff0c;需要让一个vtkDataSet中的部分单元不可见&#xff0c;查阅了一些资料大概有以下几种方式 1.通过颜色映射表来进行&#xff0c;是最正规的做法 vtkNew<vtkLookupTable> lut; //值为0不显示&#xff0c;主要是最后一个参数&#xff0c;透明度…...

拉力测试cuda pytorch 把 4070显卡拉满

import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试&#xff0c;通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小&#xff0c;增大可提高计算复杂度duration: 测试持续时间&#xff08;秒&…...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...

MySQL 部分重点知识篇

一、数据库对象 1. 主键 定义 &#xff1a;主键是用于唯一标识表中每一行记录的字段或字段组合。它具有唯一性和非空性特点。 作用 &#xff1a;确保数据的完整性&#xff0c;便于数据的查询和管理。 示例 &#xff1a;在学生信息表中&#xff0c;学号可以作为主键&#xff…...

Vite中定义@软链接

在webpack中可以直接通过符号表示src路径&#xff0c;但是vite中默认不可以。 如何实现&#xff1a; vite中提供了resolve.alias&#xff1a;通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...

【前端异常】JavaScript错误处理:分析 Uncaught (in promise) error

在前端开发中&#xff0c;JavaScript 异常是不可避免的。随着现代前端应用越来越多地使用异步操作&#xff08;如 Promise、async/await 等&#xff09;&#xff0c;开发者常常会遇到 Uncaught (in promise) error 错误。这个错误是由于未正确处理 Promise 的拒绝&#xff08;r…...

基于单片机的宠物屋智能系统设计与实现(论文+源码)

本设计基于单片机的宠物屋智能系统核心是实现对宠物生活环境及状态的智能管理。系统以单片机为中枢&#xff0c;连接红外测温传感器&#xff0c;可实时精准捕捉宠物体温变化&#xff0c;以便及时发现健康异常&#xff1b;水位检测传感器时刻监测饮用水余量&#xff0c;防止宠物…...