Java入门2-idea 第五章:IO流(java.io包中)

发布于:2025-02-11 ⋅ 阅读:(81) ⋅ 点赞:(0)
一、理解
1. 简单而言:流就是内存与存储设备之间传输数据的通道、管道。
2. 分类:
(1) 按方向 ( JVM 虚拟机为参照物 ) 【重点】
        输入流:将< 存储设备 > 中的内容读入到 < 内存 > 中。
        输出流:将< 内存 > 中的内容写入到 < 存储设备 > 中。
(2) 按单位:
        字节流:以字节为单位,可以操作所有类型的文件。
        字符流:以字符为单位,只能操作文本类型的文件。
(3) 按功能:
        节点流:具有基本的读写功能。
        过滤流:在节点流的基础上,增加新的功能。
二、字节流
1. 父类:字节流的父类 ( 抽象类 )
(1) InputStream :字节输入流
        对应的操作为读操作
        功能方法:read 方法
(2) OutputStream: 字节输出流
        对应的操作为写操作
        功能方法:write 方法
2. 字节节点流
(1) FileOutputStream :字节节点输出流 、文件字节输出流
        构造方法:
        FileOutputStream fos = new FileOutputStream("D:\\test56/a.txt");
        参数:代表操作文件的路径,如果指定的文件夹不存在,则运行报错,错误信息为:
        java.io.FileNotFoundException: D:\test5\a.txt (系统找不到指定的路径。 ) ;如果指定的
        文件不存在,系统自动创建
        绝对路径:盘符:\\ 文件夹 \\ 文件
        相对路径:文件夹/ 文件,默认在当前的项目中查找对应的文件夹内容
  功能方法 :
        write(int n):将单个字节写入文件中
        close():关闭流
(2) FileInputStream :文件字节输入流
构造方法:
        FileInputStream fis = new FileInputStream("file/c.txt");
        参数说明:参数代表操作路径,如果指定的文件不存在,则运行报错,错误信息为:
        java.io.FileNotFoundException: file\c.txt (系统找不到指定的文件。 )
功能方法:
        int read():一次性读取一个字节内容,将读取的内容作为返回值返回,达到文件尾部时,返            回-1
        close():关闭流,释放资源
3. 字节过滤流
(1) 过滤流: BufferedOutputStream/BufferedInputStream
        缓冲流, 提高 IO 效率,减少访问磁盘的次数;
        数据存储在缓冲区中,flush 是将缓存区的内容写入文件中,也可以直接 close
package testio;

import java.io.*;

public class TestFileCopyBuffered {
    public static void main(String[] args) throws IOException {
        //1.创建文件字节输入+输出流
        //(1)创建文件节点流对象
        FileInputStream fis=new FileInputStream("D:\\LJQ\\原画\\作业\\作业4\\dly.jpg");
        //(2)创建过滤流
        BufferedInputStream bis=new BufferedInputStream(fis);
        //写文件
        FileOutputStream fos=new FileOutputStream("file/buffcopy.jpg");
        BufferedOutputStream bos=new BufferedOutputStream(fos);
        //2.边写边读
        while(true){
            int n=bis.read();
            if(n==-1)break;
            bos.write(n);
        }
        //3.关闭流
        bis.close();
        bos.close();
    }
}

(2) 过滤流: ObjectOutputStream/ObjectInputStream
增强了缓冲区功能
增强了读写 8 种基本数据类型和字符串功能
增强了读写对象的功能 :
readObject() 从流中读取一个对象
writeObject() :写入对象
对象在流上进行传输的过程称为对象序列化。
对象序列化的要求: [ 重点 ]
参与对象序列化的对象对应的类,必须实现 java.io.Serializable 接口
transient 修饰的属性,不参与对象序列化
对象序列化达到文件尾部的标识:
如果运行时抛出 java.io.EOFException ,代表读取的文件达到尾部
对象序列化的细节:
如果对象的属性,是自定义类型的对象时,则该对象也必须是可序列化的
如果对集合进行对象序列化,必须保证该集合中的所有元素是可序列化的
package testio;

import java.io.*;

public class TestObjectOutputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 将对象写入对象
        Student s=new Student("秋",21,1000.0);
        //1.创建文件字节输出流对象
        FileOutputStream fos=new FileOutputStream("file/stu.txt");
        //2.包装过滤流
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(s);
        oos.close();
        //读对象
        FileInputStream fis=new FileInputStream("file/stu.txt");
        ObjectInputStream ois=new ObjectInputStream(fis);
        Object o=ois.readObject();
        System.out.println(o);
        ois.close();


    }
}

package testio;
import java.io.Serializable;
class Address implements Serializable{}
public class Student implements Serializable {
        private String name;
        private transient Integer age;
        private Double score;
        private Address a = new Address();
        public Student() {}
        public Student(String name, Integer age, Double score) {
                this.name = name;
                this.age = age;
                this.score = score;
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public Integer getAge() {
                return age;
        }
        public void setAge(Integer age) {
                this.age = age;
        }
        public Double getScore() {
                return score;
        }
        public void setScore(Double score) {
                this.score = score;
        }
        @Override
        public String toString() {
                return "Student{" +
                        "name='" + name + '\'' +
                        ", age=" + age +
                        ", score=" + score +
                        '}';
                }
        }
三、字符流
1. 字符流的父类 ( 抽象类 )
        Reader:字符输入流
        对应的操作为读操作
        功能方法:read 方法
        Writer:字符输出流
        对应的操作为写操作
        功能方法:write 方法
2. 文件字符流
(1) FileWriter 文件字符输出流,继承 Writer 中的方法:
     public void write(int n): 将单个字符写入到文件中
(2) FileReader 文件字符输入流,继承 Reader 中的方法:
     public int read(): 一次读取一个字符的内容
3. 字符过滤流
(1) BufferedReader
     功能方法,readLine() :一次性读取一行内容,返回内容为 String ,读取达到尾部,返回 -1
(2) PrintWriter
      println(参数 );
4. 桥转换流
package testio2;

import java.io.*;

public class TestInputStreamReader {
    public static void main(String[] args) {
        BufferedReader br=null;
        try{
            //1.创建文件字节流对象
            FileInputStream fis=new FileInputStream("file/k.txt");
            //2.创建桥转换流对象,设置编解码格式
            InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
            //3.创建过滤流
            br=new BufferedReader(isr);
            //4.读操作
            while(true){
                String n=br.readLine();
                if(n==null)break;
                System.out.println(n);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(br!=null){
                try{
                    br.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }

    }
}

package testio2;

import java.io.*;

// 桥转换流: ctr+A -> ctr+x -> 设置格式 -> ctr+v ->ctr+s
public class TestOutputStreamWriter {
    public static void main(String[] args) {
        PrintWriter pw = null;
        try {
            FileOutputStream fos = new FileOutputStream("file/my.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
            pw = new PrintWriter(osw);
            pw.println("嘻嘻");
            pw.println("哈哈");
            pw.print("呵呵");
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(pw !=null) {
                pw.close();
            }
        }
    }
}

四、 File
1. IO 流:对文件中的内容进行操作。 File 类:对文件自身进行操作,例如:删除文件,文件重新命名等。
2. 操作:
package testio2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class TestFile {
    public static void main(String[] args) throws IOException {
        File file = new File("file/hh.txt");
/*System.out.println(file.exists());
file.createNewFile();*/
        if(file.exists()){
            System.out.println("文件存在,则直接使用...");
            FileInputStream fis = new FileInputStream(file);
        }else{
            System.out.println("文件不存在,创建新的文件....");
            file.createNewFile();
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到