首页 > 编程语言 >JAVA IO流

JAVA IO流

时间:2024-05-27 22:48:34浏览次数:26  
标签:file JAVA String IOException IO new path public

文件基础知识:

 

创建文件的三种方法:

public static void create01(){
        //根据路径创建一个file对象
        String path="D:\\test01.txt";
        File file01=new File(path);
        try {
            file01.createNewFile();
            System.out.println("成功创建");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
public static void create02(){
        //根据父目录文件+子路径创建一个file对象
        File parent_file=new File("D:\\");
        String path="test02.txt";
        File file=new File(parent_file,path);
        try {
            file.createNewFile();
            System.out.println("成功创建");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
public static void create03(){
        //根据父目录+子路径创建一个file对象
        String parent="D:\\";
        String path="test03.txt";
        File file=new File(parent,path);
        try {
            file.createNewFile();
            System.out.println("成功创建");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

 

获取文件信息:

getName()  文件名

getAbsolutePath()  绝对路径

getParent()  父级目录

length()  文件大小【字节】

exists()  是否存在

isFile()  是否为文件

isDirectory()  是否为目录

delete()  删除文件【目录也是一种文件,也能用delete()删除】

mkdir()  创建一级目录

mkdirs()  创建多级目录

public static void create_dirs(){
        String dir_path="D:\\a\\b\\c";
        File file=new File(dir_path);
        if(file.exists()){
            System.out.println("目录已存在");
        }else{
            if(file.mkdirs()){
                System.out.println(dir_path+"创建成功");
            }else{
                System.out.println(dir_path+"创建失败");
            }
        }
    }

 

 

 

 

IO流原理及分类:

JAVA IO流原理:

  1. I/O是input/output的缩写,I/O技术用于处理数据的传输,如读/写文件、网络通讯等。
  2. Java中,对于数据的输入/输出操作是以“流(stream)”的方式进行的。
  3. 在java.io包下提供了各种“流”类和接口。
  4. 输入input:读取外部数据(磁盘、光盘等)到程序(内存)中。
  5. 输出output:将程序(内存)中的数据输出到磁盘、光盘等存储设备中。

流的分类:

  1. 按操作数据单位不同分为:字节流(8 bit)二进制文件【InputStream / OutputStream】,  字符流(按字符)文本文件 【Reader / Writer】
  2. 按数据流的流向不同分为:输入流,  输出流
  3. 按流的角色不同分为:节点流,  处理流/包装流

 

 

 

常用的类:

InputStream(字节输入流):

常用子类:

  1. FileInputStream(文件输入流)
  2. BufferedInputStream(缓冲字节输入流)
  3. ObjectInputStream(对象字节输入流)
//单个字节的读取,效率比较低
public static void read01(){ String path="D:\\hello.txt"; FileInputStream fileInputStream=null; int res=0; try { fileInputStream=new FileInputStream(path); //以这种方法读取汉字的时候会出现乱码 //因为这是一个字节一个字节读的,而在UTF-8编码中一个汉字是3个字节,以这种方法读取时,会只读取到一个汉字的第一个字节的内容 while((res=fileInputStream.read())!=-1){ System.out.print((char)res); } } catch (IOException e) { e.printStackTrace(); }finally{ try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void read02(){
        String path="D:\\hello.txt";
        FileInputStream fileInputStream=null;
        int res=0;
        byte[]data=new byte[8];//一次读取8个字节
        try {
            fileInputStream=new FileInputStream(path);
            while((res=fileInputStream.read(data))!=-1){
                System.out.print(new String(data,0,res));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

    public static void write01(){
        String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\hello_write.txt";
        FileOutputStream fileOutputStream=null;
        try {
            /**
             * fileOutputStream=new FileOutputStream(path); 会覆盖文件里原先写好的内容
             * fileOutputStream=new FileOutputStream(path,true); 会让后写的内容追加到文件后面
             */
            fileOutputStream=new FileOutputStream(path);
            //写入一个字节
            fileOutputStream.write('H');
            //写入字符串
            String str="HelloWorld";
            fileOutputStream.write(str.getBytes());

            fileOutputStream.write(str.getBytes(),0,2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

// 关于文件拷贝
public static void copy(){ String pre_path="D:\\file\\pic.jpg"; String now_path="D:\\file2\\pic_copy.jpg"; FileInputStream fileInputStream=null; FileOutputStream fileOutputStream=null; int readLen=0; try { fileInputStream=new FileInputStream(pre_path); byte[]data=new byte[1024]; fileOutputStream=new FileOutputStream(now_path); //一边读入,一边读出 while((readLen=fileInputStream.read(data))!=-1){ fileOutputStream.write(data,0,readLen); } System.out.println("拷贝成功"); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fileOutputStream!=null){ fileOutputStream.close(); } if(fileInputStream!=null){ fileInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }

 

 

FileWriter  /  FileReader :

注意:FileWriter使用之后必须关闭(close)或者刷新(flush),否则写入不到指定的文件

public static void reader(){
        String path="D:\\a_file.txt";
        int data=0;
        FileReader fileReader=null;
        try {
            fileReader = new FileReader(path);
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                fileReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
}
public static void reader02(){
        String path="D:\\a_file.txt";
        int len=0;
        char[]data=new char[8];
        FileReader fileReader=null;
        try {
            fileReader = new FileReader(path);
            while ((len = fileReader.read(data)) != -1) {
                System.out.print(new String(data,0,len));
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                fileReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
}

 

    public static void writer01(){
        String path="D:\\b_file.txt";
        FileWriter fileWriter=null;
        try {
            fileWriter=new FileWriter(path,true);
            //写单个字符
            fileWriter.write('H');
            //写入指定数组
            char[]arr={'H','E','L','L','O'};
            fileWriter.write(arr);
            //写入指定数组的指定部分
            //从0位置开始写入长度为3的内容
            fileWriter.write("你好,爪洼~".toCharArray(),0,3);
            //写入字符串
            fileWriter.write("你好,爪洼~~~");
            //写入字符串的指定位置
            fileWriter.write("你好,爪洼~~~",0,2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

 

BufferedWriter / BufferedReader ( 处理流 ):

有关键字Buffered,是一种处理流,为其包装的流增加了缓存功能,提高了输入输出的效率。

需要使用flush()才能将缓冲区中内容写入到实际的物理节点。但是,在现在版本的Java中,只需记得关闭输出流(调用close()方法),就会自动执行输出流的flush()方法,可以保证将缓冲区中内容写入。

 

public static void reader(){
        String path="D:\\a_file.txt";
        BufferedReader bufferedReader=null;
        //按行读取,效率高
        String line;
        try {
            bufferedReader=new BufferedReader(new FileReader(path));
            while((line=bufferedReader.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                //关闭时只需要关闭bufferedReader,因为底层会自动的关闭节点流
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

public static void writer() throws IOException {
        String path="D:\\c_file.txt";
        BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(path,true));
        bufferedWriter.write("hello");
        //插入一个和系统相关的换行
        bufferedWriter.newLine();
        bufferedWriter.write("hello02");
        bufferedWriter.newLine();
        bufferedWriter.write("hello03");
        bufferedWriter.close();
}

 

 

//关于文件拷贝

public static void copy(){
        String path="D:\\a_file.txt";
        String dest_path="D:\\a_file_copy.txt";
        BufferedReader bufferedReader=null;
        BufferedWriter bufferedWriter=null;
        String line;
        try {
            bufferedReader=new BufferedReader(new FileReader(path));
            bufferedWriter=new BufferedWriter(new FileWriter(dest_path));
            while((line=bufferedReader.readLine())!=null){
                //这里的读入一行不包括换行符,只是一行的内容
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

//字节流处理图片、音乐的拷贝
    public static void copy02(){
        String path="D:\\pic.jpg";
        String dest_path="D:\\pic02.jpg";
        BufferedInputStream bufferedInputStream=null;
        BufferedOutputStream bufferedOutputStream=null;
        try {
            bufferedInputStream=new BufferedInputStream(new FileInputStream(path));
            bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(dest_path));
            byte[]data=new byte[1024];
            int readLen=0;
            while((readLen=bufferedInputStream.read(data))!=-1){
                bufferedOutputStream.write(data,0,readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

 

对象处理流:

ObjectOutputStream  提供了序列化功能

ObjectInputStream     提供了反序列化功能

 

关于序列化:

  1. 序列化是指把一个Java对象变成二进制内容,本质上就是一个byte[]数组。
  2. 序列化的作用:序列化后可以把byte[]保存到文件中,或者把byte[]通过网络传输到远程。

关于反序列化:

  1. 反序列化是指把一个二进制内容(也就是byte[]数组)变回Java对象。
  2. 有了反序列化,保存到文件中的byte[]数组又可以“变回”Java对象,或者从网络上读取byte[]并把它“变回”Java对象。
public class aboutObjectOutputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //实现序列化
        about_output();
        //实现反序列化
        about_input();
    }

    public static void about_output() throws IOException{
        String path="D:\\data.dat";
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(path));
        // int ->Integer  (实现了Serializable)
        objectOutputStream.writeInt(100);
        // boolean -> Boolean  (实现了Serializable)
        objectOutputStream.writeBoolean(true);
        // char ->Character  (实现了Serializable)
        objectOutputStream.writeChar('a');
        // double ->Double  (实现了Serializable)
        objectOutputStream.writeDouble(9.5);
        // String
        objectOutputStream.writeUTF("你好,爪洼");
        // 保存一个dog对象
        objectOutputStream.writeObject(new Dog("狗",2));

        objectOutputStream.close();
    }

    public static void about_input() throws IOException, ClassNotFoundException {
        String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\data.dat";
        ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(path));
        // 读取的顺序必须和存入的数据的顺序一致
        System.out.println(objectInputStream.readInt());
        System.out.println(objectInputStream.readBoolean());
        System.out.println(objectInputStream.readChar());
        System.out.println(objectInputStream.readDouble());
        System.out.println(objectInputStream.readUTF());
        Object dog=objectInputStream.readObject();
        System.out.println("狗的信息:"+dog);

        //调用Dog  , 向下转型
        Dog res_dog=(Dog) dog;
        System.out.println("狗名: "+res_dog.getName());
        System.out.println("狗龄: "+res_dog.getAge());

        objectInputStream.close();
    }
}

 

class Dog implements Serializable {
    private String name;
    private int age;
    public Dog(String name,int age){
        this.name=name;
        this.age=age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String toString(){
        return "{"+name+","+age+"}";
    }
}

 

 

转换流 (InputStreamReader / OutputStreamWriter):

InputStreamReader: Reader的子类,可以将 InputStream(字节流) 包装成(转换) Reader(字符流)

OutputStreamWriter: Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)

 

当处理纯文本数据时,如果使用字符流效率就会更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流

public class p11_InputStreamReader {
    public static void main(String[] args) throws IOException {
        String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\hello.txt";
        // 1.把FileInputStream转化为InputStreamReader
        // 2.指定编码 utf-8
        InputStreamReader isr=new InputStreamReader(new FileInputStream(path),"utf-8");

        BufferedReader br=new BufferedReader(isr);

        String line=br.readLine();
        System.out.println(line);
        br.close();
    }
}

 

public class p12_OutputStreamWriter {
    public static void main(String[] args) throws IOException {
        String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\special_write.txt";
        OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(path),"gbk");
        osw.write("读取并转换");
        osw.close();
    }
}

 

 

标准输入输出流:

                    类型           默认设备

System.in 标准输入      InputStream         键盘

System.out 标准输出     PrintStream         显示器

 

打印流 (只有输出流,没有输入流):

printStream (字节流)

printWriter (字符流)

 

标签:file,JAVA,String,IOException,IO,new,path,public
From: https://www.cnblogs.com/ztCoding/p/18212970

相关文章

  • OpenQA.Selenium.WebDriverException The HTTP request to the remote WebDriver serv
    OpenQA.Selenium.WebDriverException:“TheHTTPrequesttotheremoteWebDriverserverforURLhttp://localhost:xxxx/sessiontimedoutafter60seconds.”1.在谷歌浏览器上加上中括号中的内容[--remote-debugging-port=9222]2.使用管理员模式打开谷歌浏览器3.重新生成......
  • 基于JAVA GUI的JDBC连接数据库
     要在JavaGUI中连接数据库,需要执行以下几个步骤:导入必要的包。你需要导入Java数据库连接相关的包,例如java.sql和javax.sql。与数据库连接相关的类和接口。  (1)DriverManger类。DriverManager类用于加载JDBD驱动并且创建其与数据库的连接。在DriverManager类中定义了......
  • java Smart系统-题库及试卷管理模块的设计与开发
    摘 要SMART系统是一个采用新思路、新架构、新技术开发出来的一个新型智能在线考试信息管理系统,该系统主要实现了学生在线考试与评估以及对各种评估信息的管理和维护。本文针对教育工作的具体需求,用struts+spring+hibernate搭建的框架为设计平台,以B/S(Browser/Server)模式......
  • [博客迁移20190713]题解 P4169 【[Violet]天使玩偶/SJY摆棋子】
    《算法竞赛》书上例题(可惜原书没代码)天使玩偶,一道好题。(书p243)我就来谈谈自己的想法吧!而总有人在这种明明可以离线处理的三维偏序问题上投机取巧。如:KDtree。蒟蒻想说,KDtree在这题复杂度是不对的。虽有剪枝,可是还是有可能遍历整棵树的(期望复杂度不靠谱)对上述看法有争议的,请跳......
  • 第七十五节 Java设计模式 - 模板方法模式
    Java设计模式-模板方法模式在模板模式中,父抽象类公开几个抽象方法供子类实现。在父抽象类中有另一个方法或几个方法使用抽象方法来实现业务逻辑。抽象方法通常用于父类所需的每个步骤。例如,为了使用新的软件,我们需要下载,安装,配置和运行。如果我们要使用模板模式来编码逻......
  • Stable Diffusion 本地部署教程(附一键整合包)
    在上一篇文章中,我们介绍了StableDiffusion模型的基本原理和本地部署的重要性。今天,我们将继续深入探讨如何在本地成功部署StableDiffusion模型,并分享一些实用的技巧和建议。一、环境准备首先,确保你的计算机满足StableDiffusion模型的基本要求。这通常包括足够的内存、......
  • Stable Diffusion 提示词入门指南
    前言本文主要讲解StableDiffusion(下文简称SD)提示词的用法,帮助大家生成更高质量的图片本章节主要讲解文生图,其他类型读者可以自行探索。同时本文主要是以StableDiffusionDiscard的形式生成图片如果各位对于图片隐私性、图片版权问题有要求,或是需要能力更加强大、......
  • 在Vision Pro 中如何把找圆区域直接赋值到斑点工具作为搜索区域
    文章目录概要整体架构流程技术细节小结概要项目需求:例如我们在项目中需要检测红圈与里面pin针的同心度(下附图),很显然红色的圆比较好找到,但是pin要抓到的话是有些不稳定的,下面我跟大家分享一个好用的项目经验。整体架构流程1.首先我们用找圆工具找到红的标注的圆2.下......
  • 在Vision pro中利用多点拟合圆的方法
    文章目录概要整体架构流程技术细节小结概要1.我们在项目中需要找圆,但是这个特征不是360°完整的圆,或者是需要多点进行拟合但是点的个数无法确定,那么就需要用到下面的方法了。整体架构流程1.首先利用找线(圆)工具找到自己需要的点2.把所有找到的点通过脚本赋值到拟合......
  • Java-JVM-运行时数据区
    参考:面试必问,JVM内存模型详解一篇文章掌握整个JVM,JVM超详细解析!!!JVM内存模型深度刨析图灵课堂-JVM极简教程(视频)0.是什么JVM是JavaVirtualMachine的缩写,即Java虚拟机。它能够运行编译后的Java字节码,使Java程序具有跨平台的特性。JVM并不会在安装JDK或JRE时自动启动,当......