【JavaSE】输入输出处理

目录

  • File类
    • 常用方法
    • 代码示例
    • 分类
    • 字节流输入流
    • 字节流输出流
    • 字节流复制粘贴效果
    • 字符流输入流
    • 字符流输出流
    • Buff版输入输出流
    • 二进制流
    • 序列化和反序列化

在这里插入图片描述

File类

File file = new File( String pathname );

常用方法

在这里插入图片描述

代码示例

	public static void main(String[] args) {
        //1.创建文件对象
        //File studentFile = new File("files");
        File studentFile = new File("files/studentInfo.txt");
        System.out.println("文件是否存在?" + studentFile.exists());
        System.out.println("是否是一个文件?" + studentFile.isFile());
        System.out.println("是否是一个目录?" + studentFile.isDirectory());
        String path = studentFile.getPath();
        System.out.println("相对路径是:" + path);
        String absolutePath = studentFile.getAbsolutePath();
        System.out.println("绝对路径是:" + absolutePath);
        System.out.println("文件的名称是:" + studentFile.getName());
        System.out.println("删除文件:" + studentFile.delete());
        System.out.println("删除之后该文件是否存在?" + studentFile.exists());
        try {
            System.out.println("重新创建studentInfo.txt文件:" + studentFile.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        File kd50File = new File("files/kd50.txt");
        System.out.println("kd50.txt的文件大小是:" + kd50File.length());

        File newFile = new File("files/kgc/kd50/wang");
        if(!newFile.exists()){
            //newFile.mkdir();//创建文件夹的
            newFile.mkdirs();//级联创建文件夹
        }
        System.out.println(newFile.exists());
        System.out.println("----------------------------------");
        /*File directory = new File("files");
        String[] files = directory.list();
        for (String s : files) {
            System.out.println(s);
        }*/
        System.out.println("----------------------------------");
        /*File directory = new File("files");
        File[] files = directory.listFiles();
        for (File file : files) {
            System.out.println(file.getName() + " -------- " + file.isFile());
        }*/
        System.out.println("----------------------------------");
        /*File directory = new File("files");
        File[] files = directory.listFiles(File::isFile);
        for (File file : files) {
            System.out.println(file.getName() + " -------- " + file.isFile());
        }*/
        System.out.println("----------------------------------");
        File directory = new File("files");
        File[] files = directory.listFiles(File::isDirectory);
        for (File file : files) {
            System.out.println(file.getName() + " -------- " + file.isDirectory());
        }
    }

通过流来读写文件:流是一组有序的数据序列,以先进先出方式发送信息的通道

分类

在这里插入图片描述在这里插入图片描述当然除了这些之外还有二进制流、对象流…

字节流输入流

public class MyFileInput {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\KD50\\project\\API\\files\\stuedntInfo.txt");
            //读取内容
            int read;
            while ((read = fis.read()) != -1) {
                System.out.print((char) read);
            }
            System.out.println();
            System.out.println("文件读取完毕");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

字节流输出流

public class MyFileOutput {
    public static void main(String[] args) {
        String words = "HelloWorld!!!";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("files/code.txt");
            byte[] bytes = words.getBytes();
            fos.write(bytes,0,bytes.length);
            fos.flush();
            System.out.println("内容输出完毕!!!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

字节流复制粘贴效果

public class CopyFile {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("files/code.txt");
            fos = new FileOutputStream("files/copy.txt",true);
            int read ;
            while ((read = fis.read())!=-1){
                fos.write(read);
            }
            fos.flush();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

字符流输入流

public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader("files/studentInfo.txt");
            int read;
            while ((read=fr.read())!=-1){
                System.out.print((char)read);
            }
            System.out.println("读取完毕");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

字符流输出流

public static void main(String[] args) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("files/kgc/info.txt");
            String words = "Hello World!!!\n" +
                    "大吉大利,今晚吃鸡!!!";
            fw.write(words);
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fw!=null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

Buff版输入输出流

	public static void main(String[] args) {
        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader("files/studentInfo.txt");
            br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine())!=null){
                System.out.println(line);
            }
            System.out.println("内容读取完毕!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
public static void main(String[] args) {
        FileReader fr = null;
        BufferedReader br = null;
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fr = new FileReader("files/studentInfo.txt");
            br = new BufferedReader(fr);
            fw = new FileWriter("files/kgc/studentInfo.txt");
            bw = new BufferedWriter(fw);
            String line;
            while ((line=br.readLine())!=null){
                bw.write(line + "\n");
            }
            System.out.println("复制完毕");
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

二进制流

public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        List<String> typeList = new ArrayList<>();
        Collections.addAll(typeList,".jpg",".png");
        File file = new File("files");
        File[] files = file.listFiles(File::isFile);
        try {
            for (File f : files) {
                if(typeList.contains(f.getName().substring(f.getName().lastIndexOf(".")))){
                    fis = new FileInputStream(file.getPath()+File.separator+f.getName());
                    dis = new DataInputStream(fis);
                    fos = new FileOutputStream(file.getPath()+File.separator+"images"+File.separator+f.getName());
                    dos = new DataOutputStream(fos);
                    int read;
                    while ((read=dis.read())!=-1){
                        dos.write(read);
                    }
                    dos.flush();
                }
            }
            System.out.println("文件全部复制完毕");
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dis!=null){
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dos!=null){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

序列化和反序列化

在这里插入图片描述

  • 注册:先读取文件中的对象(反序列化),如果为空就创建一个新的Map,不为空就将读取的流转为Map对象,每当用户注册后,将信息写到Map里,然后再把Map序列化到文件中,以实现用户注册后信息能够持久化起来。
  • 登录时从Map中进行校验
public class Menu {
    Scanner sc = new Scanner(in);
    static Map<String,User> userMap;
 
    static{
        InputStream is = null;
        ObjectInputStream ois = null;
        try {
            is = new FileInputStream("files/user/userMap.txt");
            ois = new ObjectInputStream(is);
            userMap =  (Map<String,User>)ois.readObject();
        }catch (FileNotFoundException e){
            userMap = new HashMap<>();
            //e.printStackTrace();
        }catch (IOException e){
            userMap = new HashMap<>();
            //e.printStackTrace();
        } catch (ClassNotFoundException e) {
            userMap = new HashMap<>();
            //e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public void register(){
        System.out.print("请输入用户名:");
        String userCode = sc.next();
        System.out.print("请输入密码:");
        String userPassword = sc.next();
        User user = new User(userCode,userPassword);
        userMap.put(userCode,user);
        //将注册的信息序列化
        oosObject();
    }
 
    public User login(){
        System.out.println("***************用户登录***************");
        System.out.print("请输入用户名:");
        String userCode = sc.next();
        System.out.print("请输入密码:");
        String userPassword = sc.next();
        if(!userMap.containsKey(userCode) || !userPassword.equals(userMap.get(userCode).getUserPassword())){
            return null;
        }
        return userMap.get(userCode);
    }
    private void oosObject(){
        //将注册的信息保存到外部文件中
        ObjectOutputStream oos = null;
        OutputStream os = null;
        try {
            os = new FileOutputStream("files/user/userMap.txt");
            oos = new ObjectOutputStream(os);
            oos.writeObject(userMap);
            oos.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

用户实体类

public class User implements Serializable {
    private String userCode;
    private String userPassword;
 
    public User(String userCode, String userPassword) {
        this.userCode = userCode;
        this.userPassword = userPassword;
    }
    
    public User() {
    }
 
    @Override
    public String toString() {
        return "User{" +
                "userCode='" + userCode + '\'' +
                ", userPassword='" + userPassword + '\'' +
                '}';
    }
 
    public String getUserCode() {
        return userCode;
    }
 
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
 
    public String getUserPassword() {
        return userPassword;
    }
 
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
}

测试

	public static void main(String[] args) {
        Menu menu = new Menu();
        //menu.register();
        User user = menu.login();
        if(user!=null){
            System.out.println("登录成功,登录信息为:" + user);
        }else {
            System.out.println("登录失败!");
        }
    }

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

用友U8 Cloud BlurTypeQuery SQL注入漏洞复现

0x01 产品简介 用友U8 Cloud是用友推出的新一代云ERP,主要聚焦成长型、创新型企业,提供企业级云ERP整体解决方案。 0x02 漏洞概述 用友U8 Cloud BlurTypeQuery接口处存在SQL注入漏洞,未授权的攻击者可通过此漏洞获取数据库权限,从而盗取用户数据,造成用户信息泄露。 …

基于uniapp框架的古汉语学习考试系统 微信小程序python+java+node.js+php

1、一般用户的功能及权限 所谓一般用户就是指还没有注册的过客,他们可以浏览主页面上的信息。但如果需要其它操作时&#xff0c;要登录注册&#xff0c;只有注册成功才有的权限。 2、管理员的功能及权限 用户信息的添加和管理&#xff0c;古汉语信息加和管理和学习视频添加和管…

片上网络NoC

本文大部分内容来源于王志英老师主编的《片上网络原理与设计》以及网络&#xff0c;部分内容是本人理解所得&#xff0c;若有不当之处请指教 一、概述 片上网络将报文交换的思想引入芯片内部通信机制中&#xff0c;尽管片上网络和片外网络具有一定相似性&#xff0c;但二者在…

Ethernet/IP转Modbus TCP网关

产品功能 1 YC-EIP-TCP工业级EtherNet/IP 网关 2 Modbus TCP 转 EtherNet/IP 3支持ModBus主从站 4 即插即用 无需编程 轻松组态 ,即实现数据交互 5导轨安装 支持提供EDS文件 6 EtherNET/IP与ModBus互转数据透明传输可接入PLC组态 支持CodeSys/支持欧姆龙PLC 支持罗克韦尔(AB) 典…

RISC-V SoC + AI | 在全志 D1「哪吒」开发板上,跑个 ncnn 神经网络推理框架的 demo

引言 D1 是全志科技首款基于 RISC-V 指令集的 SoC&#xff0c;主核是来自阿里平头哥的 64 位的 玄铁 C906。「哪吒」开发板 是全志在线基于全志科技 D1 芯片定制的 AIoT 开发板&#xff0c;是目前还比较罕见的使用 RISC-V SoC 且可运行 GNU/Linux 操作系统的可量产开发板。 n…

代码随想录算法训练营第25天—回溯算法05 | *491.递增子序列 *46.全排列 47.全排列 II

*491.递增子序列 https://programmercarl.com/0491.%E9%80%92%E5%A2%9E%E5%AD%90%E5%BA%8F%E5%88%97.html 视频讲解&#xff1a;https://www.bilibili.com/video/BV1EG4y1h78v 考点 回溯子集去重 我的思路 暴力法&#xff0c;不进行去重&#xff0c;仅在最后加入结果时判断当…

探索比特币现货 ETF 对加密货币价格的潜在影响

撰文&#xff1a;Sean&#xff0c;Techub News 文章来源Techub News&#xff0c;搜Tehub News下载查看更多Web3资讯。 自美国比特币现货交易所交易基金&#xff08;ETF&#xff09;上市以来&#xff0c;比特币现货 ETF 的相关信息无疑成为了影响比特币价格及加密货币市场走向…

提升 Node.js 服务端性能:Fastify 框架

微信搜索“好朋友乐平”关注公众号。 1. fastify Fastify 是一个高效且快速的 Node.js web 框架&#xff0c;专为提供最佳的性能而设计。它是相对较新的&#xff0c;但已经因其高性能和低开销而受到许多开发者的欢迎。Fastify 提供了一个简洁的开发体验&#xff0c;同时支持快…

【基于Ubuntu20.04的Autoware.universe安装过程】方案一:虚拟机 | 详细记录 | Vmware | 全过程图文 by.Akaxi

目录 一、Autoware.universe背景 二、虚拟机配置 三、Ubuntu20.04安装 四、GPU显卡安装 五、ROS2-Galactic安装 六、ROS2-dev-tools安装 七、rmw-implementation安装 八、pacmod安装 九、autoware-core安装 十、autoware universe dependencies安装 十一、安装pre-c…

光速入门spark(待续)

目录 Spark概述Spark 是什么Spark VS Hadoop (MapReduce)Spark or HadoopSpark四大特点速度快易于使用通用性强运行方式 Spark 框架模块&#xff08;架构&#xff09;Spark的运行模式Spark的架构角色 Spark环境搭建LocalStandaloneSpark程序运行层次结构 Spark on YARN部署模式…

有适合短视频剪辑软件的吗?分享4款热门软件!

在数字时代&#xff0c;短视频已成为人们获取信息、娱乐消遣的重要形式。随着短视频行业的蓬勃发展&#xff0c;市场上涌现出众多短视频剪辑软件&#xff0c;它们功能各异&#xff0c;各具特色。本文将为您详细介绍几款热门短视频剪辑软件&#xff0c;助您轻松掌握短视频剪辑技…

Linux拉取SVN服务器代码

1. window10系统上安装了Ubuntu&#xff0c;然后在Ubuntu上拉去SVN服务器的代码&#xff0c;我这是用VScode连接的ubuntu 终端Terminal&#xff0c;我这里相当于有三台电脑了&#xff0c;公司的服务器上windows的&#xff0c;svn代码就是在这台服务器里面&#xff0c;然后我又在…

idea集成git(实用篇)

0.Git常用命令 Git常用命令-CSDN博客 1.下载git Git - Downloads 一路傻瓜式安装即可&#xff08;NEXT&#xff09; 2.软件测试 在Windows桌面空白处&#xff0c;点击鼠标右键&#xff0c;弹出右键菜单 Git软件安装后&#xff0c;会在右键菜单中增加两个菜单 Git GUI He…

ClickHouse 指南(三)最佳实践 -- 跳数索引

Data Skipping Indexes Data Skipping Indexes 2 1、简介 影响ClickHouse查询性能的因素很多。在大多数情况下&#xff0c;关键因素是ClickHouse在计算查询WHERE子句条件时是否可以使用主键。因此&#xff0c;选择适用于最常见查询模式的主键对于有效的表设计至关重要。 然…

华为OD机试真题-靠谱的车-2023年OD统一考试(C卷)---Python3-开源

题目&#xff1a; 考察内容&#xff1a; 思维转化&#xff0c;进制转化&#xff0c;9进制转为10进制&#xff0c;在4的位置1&#xff0c;需要判断是否大于4 代码&#xff1a; """ 题目分析&#xff1a; 9进制转化为10进制23-25 39-50 399-500输入&#xff1a…

系统性能提升70%!华润万家某核心系统数据库升级实践

华润万家是华润集团旗下优秀零售连锁企业&#xff0c;业务覆盖中国内地及香港市场&#xff0c;面对万家众多业务需求和互相关联的业务环境&#xff0c;亟需加强各业务耦合性&#xff0c;以适应线上、线下、物流、财务等各个业务环境的快速发展。 随着信息技术的快速发展和数字化…

blender bvh显示关节名称

导入bvh&#xff0c;菜单选择布局&#xff0c;右边出现属性窗口&#xff0c; 在下图红色框依次点击选中&#xff0c;就可以查看bvh关节名称了。

ReentrantLock详解-可重入锁-默认非公平

ReentrantLock是Java中的一个可重入锁&#xff0c;也被称为“独占锁”。它基于AQS&#xff08;AbstractQueuedSynchronizer&#xff09;框架实现&#xff0c;是JDK中提供的一种线程并发访问的同步手段&#xff0c;与synchronized类似&#xff0c;但具有更多特性。 ReentrantLo…

【Linux】进程优先级和Linux内核进程调度队列的简要介绍

进程优先级 基本概念查看系统进程修改进程的优先级Linux2.6内核进程调度队列的简要介绍和进程优先级有关的概念进程切换 基本概念 为什么会存在进程优先级&#xff1f;   进程优先级用于确定在资源竞争的情况下&#xff0c;哪个进程将被操作系统调度为下一个运行的进程。进程…

【java】15:抽象类

当父类的一些方法不能确定时,可以用abstract关键字来修饰该方法&#xff0c;这个方法就是抽象方法&#xff0c;用abstract来修饰该类就是抽象类。 //我们看看如何把Animal做成抽象类&#xff0c;并让子类Cat类实现。 abstract class Animal{ String name; int age; abstract p…
最新文章