Java——I/O流(File类、节点流、缓冲流、转换流、对象流)

1. File类的使用

1.1 概述

  • java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关
  • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。
    如果需要访问文件内容本身,则需要使用 输入/输出流。
  • 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对
    象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
  • File对象可以作为参数传递给流的构造器

创建File类的实例

在这里插入图片描述
在这里插入图片描述

//单元测试中的相对路径,相对于当前module
//main方法中的相对路径,相对于当前工程
File file = new File("hello.txt");

//绝对路径
File file1 = new File("d:\\JAVA_WORK\\info");
File file2 = new File("d:" + File.separator + "example" +
 					   File.separator + "info.txt");
File file3 = new File("d:/JAVA_WORK");
File file1 = new File("D:\\JAVA_WORK","info");
File file2 = new File(file1,"hello.txt");

1.2 使用

在这里插入图片描述
其中,重命名方法public boolean renameTo(File dest),若file1.renameTo(file2),要想保证返回 true,需要 file1 在硬盘中是存在的,且 file2 不能在硬盘中存在。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. I/O流

2.1 概述

  • Java程序中,对于数据的输入/输出操作以“流(stream)” 的
    方式进行。
  • java.io包下提供了各种“流”类和接口,用以获取不同种类的
    数据,并通过标准的方法输入或输出数据。
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

2.2 节点流(文件流)

2.2.1 字符流

① 将当前Module下的 hello.txt 文件内容读入程序中,并输出到控制台

  • read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
  • 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
  • 读入的文件一定要存在,否则就会报FileNotFoundException
	@Test
    public void testFileReader() throws Exception{
    	FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //2.提供具体的流
            fr = new FileReader(file);

            //3.数据的读入
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的关闭操作
            try {
                if(fr != null) fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

//对read()操作升级:使用read的重载方法
    @Test
    public void testFileReader1()  {
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");

            //2.FileReader流的实例化
            fr = new FileReader(file);

            //3.读入的操作
            //read(char[] cbuf)
            //返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
            while((len = fr.read(cbuf)) != -1){
                //方式一:
                //错误的写法
//                for(int i = 0;i < cbuf.length;i++){
//                    System.out.print(cbuf[i]);
//                }
                //正确的写法
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }
                //方式二:
                //错误的写法,对应着方式一的错误的写法
//                String str = new String(cbuf);
//                System.out.print(str);
                //正确的写法
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4.资源的关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

③ 从内存中写出数据到硬盘的文件里

  • 输出操作,对应的File可以不存在的。并不会报异常
  • File 对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
  • File对应的硬盘中的文件如果存在
    • 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file),则对原有文件的覆盖
    • 如果流使用的构造器是:FileWriter(file,true),则不会对原有文件覆盖,而是在原有文件基础上追加内容
	@Test
    public void testFileWriter() {
        FileWriter fw = null;
        try {
            //1.提供File类的对象,指明写出到的文件
            File file = new File("hello1.txt");

            //2.提供FileWriter的对象,用于数据的写出
            fw = new FileWriter(file,false);

            //3.写出的操作
            fw.write("I have a dream!\n");
            fw.write("you need to have a dream!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流资源的关闭
            if(fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

2.2.2 字节流

	/*
    实现对图片的复制操作
     */
	@Test
    public void testFileInputstream(){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            File srcFile = new File("test.png");
            File destFile = new File("test1.png");

            fileInputStream = new FileInputStream(srcFile);
            fileOutputStream = new FileOutputStream(destFile);

            byte[] b = new byte[10];
            int len;
            while ((len=fileInputStream.read(b))!=-1){
                fileOutputStream.write(b,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileInputStream!=null) fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fileOutputStream!=null) fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2.3 缓冲流(处理流的一种)

2.3.1 字节流

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

作用:提供流的读取、写入的速度;原理:内部提供了一个缓冲区

	/*
    实现非文本文件的复制
     */
    @Test
    public void BufferedStreamTest() throws FileNotFoundException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File("爱情与友情.jpg");
            File destFile = new File("爱情与友情3.jpg");
            
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
                //刷新缓冲区
                //bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            //说明:关闭外层流的同时,内层流也会自动的进行关闭。
            //所以关于内层流的关闭,可省略
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

2.3.2 字符流

	@Test
    public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));

            //读写操作
            //方式一:使用char[]数组
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//    //            bw.flush();
//            }

            //方式二:使用String
            String data;
            while((data = br.readLine()) != null){
                //换行方法一:
                //写出的data中不包含换行符
                //bw.write(data + "\n");
                
                //换行方法二:
                bw.write(data);
                //提供换行的操作
                bw.newLine();

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(bw != null){

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

2.3.3 总结

抽象基类节点流(或文件流)缓冲流(处理流的一种)
InputStreamFileInputStream——read(byte[] buffer)BufferedInputStream——read(byte[] buffer)
OutputStreamFileOutputStream——write(byte[] buffer,0,len)BufferedOutputStream write(byte[] buffer,0,len) / flush()
ReaderFileReader ——read(char[] cbuf)BufferedReader——read(char[] cbuf) / readLine()
WriterFileWriter——write(char[] cbuf,0,len)BufferedWriter——write(char[] cbuf,0,len) / flush()

2.4 转换流(处理流的一种)

  • 转换流提供了在字节流和字符流之间的转换
  • Java API提供了两个转换流(属于字符流):
    • InputStreamReader:将一个字节的输入流 转换为字符的输入流
    • OutputStreamWriter:将一个字符的输出流 转换为字节的输出流
	/*
    InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
    */
    @Test
    public void InputStreamReaderTest(){
        InputStreamReader inputStreamReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            //参数2指明了字符集
            //具体使用哪个字符集,取决于文件hello.txt保存时使用的字符集
            inputStreamReader = new InputStreamReader(new FileInputStream("hello.txt"), "UTF-8");
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream("hello_gbk.txt"),"GBK");
            char[] cbuf = new char[1024];
            int len;

            while ((len = inputStreamReader.read(cbuf))!=-1){
                outputStreamWriter.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(inputStreamReader!=null) inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(outputStreamWriter!=null) outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.5 标准输入、输出流

  • System.inSystem.out分别代表了系统标准的输入和输出设备
  • 默认输入设备是: 键盘, 输出设备是:显示器
  • System.in的类型是InputStream
  • System.out的类型是PrintStream,其是OutputStream的子类
  • 重定向:通过System类的setInsetOut方法对默认设备进行改变。
    • public static void setIn(InputStream in)
    • public static void setOut(PrintStream out)

FilterOutputStream 的子类

例 题
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续
进行输入操作,直至当输入“e”或者“exit”时,退出程序:

public static void main(String[] args) {

        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            while (true) {
                System.out.println("请输入字符串:");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                    System.out.println("程序结束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2.6 打印流

实现将 基本数据类型 的数据格式转化为 字符串 输出

在这里插入图片描述

@Test
    public void test2() {
        
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
            // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }

            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
    }

2.7 数据流

在这里插入图片描述

	//练习:将内存中的字符串、基本数据类型的变量写出到文件中。
    @Test
    public void test3() throws IOException {
		DataOutputStream dos = null;
        try {
        	dos = new DataOutputStream(new FileOutputStream("data.txt"));
            dos.writeUTF("Tom");
        	dos.flush();//刷新操作,将内存中的数据写入文件
        	dos.writeInt(23);
        	dos.flush();
        	dos.writeBoolean(true);
        	dos.flush();
        
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (dos!= null) {
                dos.close();
            }
        }
    }
    
    /*
    将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
    注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
     */
    @Test
    public void test4() throws IOException {
      
		DataInputStream dis = null;
        try {
        	dis = new DataInputStream(new FileInputStream("data.txt"));
        	String name = dis.readUTF();
        	int age = dis.readInt();
        	boolean isMale = dis.readBoolean();
        	
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (dis!= null) {
                dis.close();
            }
        }
    }

2.8 对象流

2.8.1 对象序列化

① 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从
而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传
输到另一个网络节点。 (当其它程序获取了这种二进制流,就可以恢复成原
来的Java对象)
② 序列化优点:可将任何实现了Serializable接口的对象转化为字节数据,
使其在保存和传输时可被还原
③ 序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返
回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是
JavaEE 平台的基础
④ 如果需要让某个对象支持序列化机制,则必须让 对象所属的类及其属性 是可
序列化的(默认基本数据类型已是可序列化),为了让某个类是可序列化的,该类须实现如下两个接口之一,否则会抛NotSerializableException异常:

  • Serializable
  • Externalizable

⑤ 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:

  • private static final long serialVersionUID;
  • serialVersionUID用来表明类的不同版本间的兼容性。 简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
  • 如果类没有显示定义次静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。 若对类做了修改, serialVersionUID可能发生变化,故建议显式声明。

⑥ 简单来说, Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时, JVM会把传来的字节流中的
serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异
常。 (InvalidCastException)

2.8.2

ObjectInputStreamOjbectOutputSteam

  • 用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可
    以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来(持久化)。

序列化: 用ObjectOutputStream类保存基本类型数据或对象的机制(写出)
反序列化: 用ObjectInputStream类读取基本类型数据或对象的机制(写入)

注:ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量。

	/*
    序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
    使用ObjectOutputStream实现
     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;

        try {
            //1.
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            //2.
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();//刷新操作
            
			//	Person类已实现Serializable接口
			//且声明了serialVersionUID
            oos.writeObject(new Person("王铭",23));
            oos.flush();

            oos.writeObject(new Person("张学良",23,1001,new Account(5000)));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                //3.
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    /*
    反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    使用ObjectInputStream来实现
     */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String) obj;

            Person p = (Person) ois.readObject();
            Person p1 = (Person) ois.readObject();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

2.9 随机存取文件流

RandomAccessFile 声明在 java.io 包下,但直接继承于java.lang.Object类。 并且它实现了DataInputDataOutput这两个接口,即这个类既作为输出流,也可作为输入流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值