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

news2024/9/22 8:55:11

目录

一、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 和 so
        System.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 和 so
        System.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.coloradmin.cn/o/2139335.html

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

相关文章

【有啥问啥】自动提示词工程(Automatic Prompt Engineering, APE):深入解析与技术应用

自动提示词工程&#xff08;Automatic Prompt Engineering, APE&#xff09;&#xff1a;深入解析与技术应用 引言 随着大语言模型&#xff08;LLM&#xff09;如 GPT、BERT 等的快速发展&#xff0c;如何高效地与这些模型进行互动成为了重要的研究方向之一。提示词&#xff…

阿里P8和P9级别有何要求

阿里巴巴的P8和P9级别&#xff0c;代表着公司的资深技术专家或管理者岗位&#xff0c;要求候选人具有丰富的职业经历、深厚的技术能力以及出色的领导力。以下是对P8和P9级别的要求、考察点以及准备建议的详细分析。 P8 级别要求 1. 职业经历&#xff1a; 8年以上的工作经验&a…

PCIe进阶之TL:Common Packet Header Fields TLPs with Data Payloads Rules

1 Transaction Layer Protocol - Packet Definition TLP有四种事务类型:Memory、I/O、Configuration 和 Messages,两种地址格式:32bit 和 64bit。 构成 TLP 时,所有标记为 Reserved 的字段(有时缩写为 R)都必须全为0。接收者Rx必须忽略此字段中的值,PCIe Switch 必须对…

响应式网站的网站建设,需要注意什么?

响应式网站建设需要注意多个方面&#xff0c;以确保网站能够在各种设备和屏幕尺寸上提供一致且良好的用户体验。下面详细介绍响应式网站建设的注意事项&#xff1a; 响应式网站的网站建设&#xff0c;需要注意什么? 考虑多终端适配 设计样式&#xff1a;在设计响应式网站时&…

豆包MarsCode | 一款智能编程助手开发工具

豆包MarsCode | 一款智能编程助手开发工具 豆包MarsCode 是基于豆包大模型的智能开发工具&#xff0c;提供 Cloud IDE 和 AI 编程助手&#xff0c;支持代码补全、智能问答、代码解释与修复&#xff0c;兼容主流编程工具与 100 种编程语言&#xff0c;助力编程更智能便捷 豆包 M…

InterPro蛋白质结构域数据下载

前言 偶然发现InterPro数据库挺不错的。 之前使用selenium爬取了AlphaFlod数据&#xff0c;于是也想试试把InterPro的结构域数据爬取一下。 结果发现官方已经给好了代码&#xff0c;真是太善解人意了。 当然&#xff0c;想要批量下载还需要魔改一下官方代码。 步骤一&#…

【初阶数据结构】排序

目录 一、排序的概念及其运用 1.1排序的概念 1.2常见的排序算法 二、常见排序算法的实现 2 .1插入排序 2 .1.1基本思想&#xff1a; 2.1.2直接插入排序&#xff1a; 算法复杂度&#xff1a; 最坏情况&#xff1a; 最好的情况&#xff1a; 直接插入排序的特性总结&…

思维商业篇(2)—业务第一性

思维商业篇(2)—业务第一性 前言 第一性原理是超过因果律的第一因&#xff0c;且是唯一因。 第一性原理是事物唯一的源头&#xff0c;是抽象。是看透事物的本质&#xff0c;要把事物分解成最基本的组成&#xff0c;从源头上去解决问题。 对于一个企业来说&#xff0c;第一性…

01,大数据总结,zookeeper

1 &#xff0c;zookeeper &#xff1a;概述 1.1&#xff0c;zookeeper&#xff1a;作用 1 &#xff0c;大数据领域 &#xff1a;存储配置数据   例如&#xff1a;hadoop 的 ha 配置信息&#xff0c;hbase 的配置信息&#xff0c;都存储在 zookeeper 2 &#xff0c;应用领…

PXE服务

一.PXE服务的功能介绍 1.无盘启动&#xff1a;PXE允许计算机在没有本地存储设备的情况下启动操作系统。这对于构建无盘工作站非常有用&#xff0c;因为计算机可以直接从网络加载操作系统和其他应用程序1。 2.远程安装操作系统&#xff1a;PXE技术可以用于远程安装操作系统&…

C++11的部分新特性

目录 1.列表初始化 1.1 { } 初始化 1.2 std::initializer_list 2.声明 2.1 auto 2.2 decltype 2.3 nullptr 3. 范围for 4.STL中的一些变化 5.右值引用与移动语义 5.1 左值引用与右值引用 5.2 左值引用与右值引用的比较 5.3 右值引用使用场景 5.4 完美转发 6.新的…

操作系统week2

操作系统学习 二.处理机管理 19.生产者-消费者问题 问题&#xff1a; 代码&#xff1a; 20.多生产者-多消费者问题 实现&#xff1a; 21.吸烟者问题(单生产者-多消费者) 问题&#xff1a; 实现&#xff1a; 22.读者-写者问题 问题&#xff1a; 读优先的代码&…

CentOS7更换阿里云yum更新源

目前CentOS内置的更新安装源经常报错无法更新&#xff0c;或者速度不够理想&#xff0c;这个时候更换国内的镜像源就是一个不错的选择。 备份内置更新源 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 下载阿里云repo源&#xff08;需要系统…

Cubieboard2(三) 系统构建 —— WSL Ubuntu 中挂载 U 盘(SDCard)

文章目录 1 WSL Ubuntu 中挂载 U 盘(SDCard)2 usbipd 搭建虚拟机与宿主机 USB 通信桥梁3 WSL 内核添加 USB 设备驱动3.1 编译 WSL Linux 内核3.2 挂载 USB(SDCard) 设备 附录&#xff1a;WSL 操作命令附录&#xff1a;git 仓库检出 1 WSL Ubuntu 中挂载 U 盘(SDCard) Linux 驱动…

使用OpenFeign在不同微服务之间传递用户信息时失败

文章目录 起因原因解决方法&#xff1a; 起因 从pay-service中实现下单时&#xff0c;会调用到user-service中的扣减余额。 因此这里需要在不同微服务之间传递用户信息。 但是user-service中始终从始至终拿不到user的信息。 原因 在pay-service中&#xff0c;不仅要Enable O…

YOLO学习笔记 | YOLO目标检测算法(YOLO-V2)

github&#xff1a;https://github.com/MichaelBeechan CSDN&#xff1a;https://blog.csdn.net/u011344545 YOLO-V2 V1与V2区别Batch Normalization更大分辨率YOLO-V2网络结构 V1与V2区别 V2更强更快 Batch Normalization 更大分辨率 YOLO-V2网络结构

顺序栈讲解

文章目录 &#x1f34a;自我介绍&#x1f34a;顺序栈讲解生活中的例子栈的基本概念入栈和出栈 你的点赞评论就是对博主最大的鼓励 当然喜欢的小伙伴可以&#xff1a;点赞关注评论收藏&#xff08;一键四连&#xff09;哦~ &#x1f34a;自我介绍 Hello,大家好&#xff0c;我是小…

《ImageNet Classification with Deep Convolutional Neural Networks》论文导读

版权声明 本文原创作者:谷哥的小弟作者博客地址:http://blog.csdn.net/lfdfhl《ImageNet Classification with Deep Convolutional Neural Networks》是一篇在深度学习领域具有重要影响力的论文,由Alex Krizhevsky、Ilya Sutskever和Geoffrey E. Hinton等人撰写。该论文主要…

窗口嵌入桌面背景层(vb.net,高考倒计时特供版)

开发思路 根据系统生成高考倒计时的具体时间&#xff0c;附加江苏省省统考的时间生成算法&#xff0c;并且用户可以根据实际情况调整前后30天&#xff0c;具有丰富多彩的图片库和强大的自定义功能&#xff0c;效果图见P3 目前程序处于正式版的1.4版本&#xff0c;本程序由本作…

【信创】Linux上图形化多ping工具--gping的编译安装与打包 _ 统信 _ 麒麟 _ 方德

原文链接&#xff1a;【信创】图形化多ping工具gping的编译安装与打包 | 统信 | 麒麟 | 方德 Hello&#xff0c;大家好啊&#xff01;今天给大家带来一篇关于在Linux操作系统上使用gping的文章。gping是一款非常实用的命令行工具&#xff0c;它将传统的ping命令进行了可视化改进…