18、IO流:

18、IO流:

这一章很枯燥无聊~

文件:

什么是文件:

文件,对我们并不陌生,文件时保存数据的地方,比如我们经常使用的word文档,txt文档,excel文档…都是文件。它既可以保存一张图片,也可以保持视频,声音。

文件流:

文件在程序中是以流的形式操作的。

  • 流:数据从数据源(文件)和程序(内存)之间经历的路径;
  • 输入流:数据从数据源(文件)到程序(内存)的路径;
  • 输出流:数据从程序(内存)到数据源(文件)的路径。

常用的文件操作:

创建文件对象相关构造器和方法:

相关方法:

  • new File(String pathname); // 根据路径构建一个File对象
  • new File(File parent, String child); // 根据父目录文件 + 子路径构建
  • new File(String parent, String child); // 根据父目录 + 子路径构建
  • File_Object.creatNewFile(); // 创建新文件。

new File()是在内存中创建出了文件,但是没有将这个文件创建到磁盘中,我们需要使用creatNewFile()来将文件创建到磁盘中。

案例代码:

package com.jiangxian;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */

public class FileCreate {
    public static void main(String[] args) {
        
    }

    
    @Test // Test一开始会是红色,光标挪至此处,然后按下Alt + Enter,将需要的下载Junit下来。
    // 方式1 new File(String pathname)
    public void creat01(){
        String filepath = "e:\\news1.txt";
        File file = new File(filepath);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void creat02(){
        File parentFile = new File("e:\\");
        String fileName = "news2.txt";
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void creat03(){
        String parentPath = "e:\\";
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

获取文件的相关信息:

getName(获取文件名)、getAbsolutePath(获取绝对路径)、getParent(获取父目录)、length、exists、isFile(是否是文件)、isDirectory(是否是目录——文件夹)

应用案例:

package com.jiangxian;

import org.junit.jupiter.api.Test;
import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 * 演示如何获取文件的大小,文件名,路径,父File,是文件还是目录(目录本质也是文件),是否存在
 *
 */


public class FileInformation {
    public static void main(String[] args) {

    }
    @Test
    public void info(){
        // 先创建文件对象:
        File file =  new File("e:\\news1.txt");

        // 调用相应的方法,得到对应信息;
        System.out.println("文件名为:" + file.getName());
        System.out.println("文件绝对路径为:" + file.getAbsolutePath());
        System.out.println("文件父级目录:" + file.getParent());
        System.out.println("文件大小(字节):" + file.length());
        System.out.println("文件是否存在:" + file.exists());
        System.out.println("是否是一个文件:" + file.isFile());
        System.out.println("是否是一个目录:" + file.isDirectory());
        
    }
}

目录操作和文件删除:

  • mkdir 创建一级目录;
  • mkdirs 创建多级目录;
  • delete 删除空目录或文件(若要删除目录,其必须是空的,若由内容必须先删除里面的文件)。

应用案例演示:

package com.jiangxian;

import org.junit.jupiter.api.Test;

import java.io.File;

/**
 * @author JiangXian~
 * @version 1.0
 */

public class FileDirectory {
    public static void main(String[] args) {

    }

    @Test
    public void Directory_1(){
        File file = new File("e:\\news1.txt");
        if(file.exists()){
            file.delete();
            System.out.println("删除成功!");
        }
    }

    @Test
    public void Directory_2(){
        File file = new File("e:\\demo02.txt");
        if(file.exists()){
            file.delete();
            System.out.println("文件删除成功!");
        }else {
            System.out.println(file.getName() + "文件不存在。");
        }
    }

    @Test
    public void Directory_3(){
        String directoryPath = "e:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if(file.exists()){
            System.out.println(file.getName() + "目录已经存在");
        }else{
            file.mkdirs();
            // 输出的是最后一个目录名。
            System.out.println(file.getName() + "目录不存在,现已创建!");
        }
    }
}


IO流原理及流的分类:

Java IO流原理:

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

流的分类:

  • 按操作数据单位不同分为:字节流(8bit=1Byte)擅长读写二进制文件;字符流(按字符) 擅长读写文本文件
  • 按数据流的流向不同分为:输入流,输出流;
  • 按流的角色的不同分为:节点流,处理流/包装流。
(抽象基类)字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter
  1. Java 的 IO流共设计40多个类,实际上非常规则,都是从如上四个抽象基类派生的;
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀的。

怎么去理解流:

程序(内存):可以理解为我们!假设我们在网上买了东西;

文件(磁盘):可以理解为我们买东西的网店;

流:可以理解为快递员。(网店需要通过快递员才能把物品交给我们~)。


FileInputStream 介绍:

是抽象类 InputStream 的子类

构造方法:

  • FileInputStream(File file):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定;
  • FileInputStream(fileDescriptor fdObj):通过使用文件描述符 fdObj 创建一个 FileInputStream,该文件描述表示到文件系统中某个实际文件的现有连接;
  • FileInputStream(String name):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 推定。

当文件和一个 FileInputStream 对象(流)关联起来后,我们就使用这个对象去操作这个文明。

方法概要:

  • read():从输入流中读取一个字节;若读到文件末尾返回-1,返回的值是当前字母对应的ASCII值
  • read(byte[] b):从输入流中一次性读取最多b.length的字节到数组b中;若到文件末尾返回-1,否则返回的值是读取的字节长度
  • read(byte[] b, int off, int len):从输入流中一次性将最多len个的字节读取到数组b中。
  • close():关闭此文件输入流并释放与此流相关的所有系统资源。

案例:

原始:

忘记添加close()

package com.jiangxian.InputStream_;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class FileInputStream_ {
    public static void main(String[] args) {
    }

    @Test
    public void input_(){
        String filePath = "D:\\Code\\Project\\javacode\\chapter18\\src\\com\\jiangxian\\hello.txt";
        File file = new File(filePath);
        int read = 0;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            // 从该输入流中每次读取一个字节的数据,若没有输入可用,此方法将终止
            // 若返回-1表示读取完毕,否则返回的是ASCII码
            while((read = fileInputStream.read()) != -1){
                System.out.print((char)read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

修改后:
package com.jiangxian.InputStream_;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }


    @Test
    public void input_(){
        String filePath = "D:\\Code\\Project\\javacode\\chapter18\\src\\com\\jiangxian\\hello.txt";
        File file = new File(filePath);
        int read = 0;
        // 让其为空不会报错
        FileInputStream fileInputStream = null;
        try {
            // 此处会执行修改
            // FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream = new FileInputStream(file);
            // 从该输入流中每次读取一个字节的数据,若没有输入可用,此方法将终止
            // 若返回-1表示读取完毕,否则返回的是ASCII码
            while((read = fileInputStream.read()) != -1){
                System.out.print((char)read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{ // 无论操作如何,都要保证关闭一次!
            // 当我们完成读写后,要关闭文件流,释放资源
            // 但是我们发现,我们定义的fileInputStream是在try代码块内的,
            // 作用域到不了finally,怎么办呢,在try外定义,让其为空
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}



但是此处要是文件里是汉字,会是乱码,为什么呢?因为我们使用的是UTF-8编码,字母是1个字节,但是汉字是3个字节,所以会是乱码(想要读取汉字得要使用字符流处理!)

多字节读取:

    @Test
    public void input_2(){ // 这样读取效率高
        String filePath = "D:\\Code\\Project\\javacode\\chapter18\\src\\com\\jiangxian\\hello.txt";
        File file = new File(filePath);
        // 字节数组
        byte[] buffer = new byte[8];
        // 定义实际接受的长度
        int len = 0;
        FileInputStream fileInputStream = null;
        try {
            // 此处会执行修改
            // FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream = new FileInputStream(file);
            // 从该输入流中每次读取一个字节的数据,若没有输入可用,此方法将终止
            // 若返回-1表示读取完毕,否则返回的是ASCII码
            while((len = fileInputStream.read(buffer)) != -1){
                System.out.print(new String(buffer,0,len)); // 将byte数组转换为String
                // 为什么不直接toSting呢?buffer中的数据每次不会清空,而是覆盖
                // 当最后读入的数据<buffer.length的时候,会有一段数据是无用的
                // 将其也转换为字符串是不正确的答案
                // 所以需要对转换的末尾位置做一个确定。
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{ // 无论操作如何,都要保证关闭一次!
            // 当我们完成读写后,要关闭文件流,释放资源
            // 但是我们发现,我们定义的fileInputStream是在try代码块内的,
            // 作用域到不了finally,怎么办呢,在try外定义,让其为空
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

FileOutputStream介绍:

构造方法:

  • FileOutputStream(File file);
    • 创建一个指向 File 对象表示的文件输出流。
  • FileOutputStream(String name);
    • 创建一个指向具有指定名称文件的写入输入流。
  • FileOutputStream(File file, boolean append);
    • 创建一个指向 File 对象表示的文件输出流,此时的模式是追加,而不是覆盖(光标在文件末尾而不是开头)。
  • FileOutputStream(String name, boolean append);
    • 创建一个指向具有指定名称文件的写入输入流,此时的模式是追加,而不是覆盖(光标在文件末尾而不是开头)。
  • FileOutputStream(FileDescriptor fdObj);

方法概述:

  • close():关闭此文件输出流并释放与此有关的所有系统资源(只有使用完close才真正写入到文件,否则只是写入了文件输出流中);
  • write(int b):将指定字节写入此文件输出流中;
  • write(byte[] b):将b,length个字节从指定数组中写入
  • write(byte[] b,int off, int len):将指定b从偏移off处开始的len个字节写入文件输出流。

案例:

import org.junit.jupiter.api.Test;

import java.io.*;

public class FileOutputStream_ {
    public static void main(String[] args) {

    }

    /*
    演示如何使用FileOutputStream 将输入写到文件中
    若文件不存在,就创建它
     */
    @Test
    public void out_(){ // 写入单个字符
        FileOutputStream fos = null;
        String filePath = "d:\\a.txt";
        try {
            fos = new FileOutputStream(filePath);
            fos.write('a'); // char 会自动地转换为 int
            // fos.write('H'),此时会覆盖之前的a
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void out2(){ // 写入字符串
        FileOutputStream fos = null;
        String filePath = "d:\\a.txt";
        try {
            fos = new FileOutputStream(filePath);
            String str = "Hello,World!";
            // str.getBytes可以把字符串转换成一个字节数组。
            fos.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void out3(){ // 不覆盖,在后面追加
        FileOutputStream fos = null;
        String filePath = "d:\\a.txt";
        try {
            fos = new FileOutputStream(filePath,true);
            String str = "\nHello,World!";
            // str.getBytes可以把字符串转换成一个字节数组。
            fos.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


文件拷贝:

案例:

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy_ {
    public static void main(String[] args) {
    }

    @Test
    public void copy(){
        String srcPath = "e:\\self_study\\NoteBook\\mg.png";
        String destPath = "e:\\self_study\\NoteBook\\Java\\mg.png";
        // 创建输入流,是为了将文件读入到程序
        FileInputStream fis = null;
        // 创建输出流,为了将文件输出到指定位置
        FileOutputStream fos = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        // 应该是一边读取,一边写入
        try {
            fis = new FileInputStream(srcPath);
            fos = new FileOutputStream(destPath);
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

可能有人会理解不了,不是说write会覆盖吗,为什么能把整个图片拷贝过去呀!我们要明白,覆盖是对流的,而流是整个对象,而不是write这个方法,所以只要我们没有.close那么在同一个输出流中就不会覆盖。


FileReader 和 FileWriter

FileReader:

继承的是InputStreamReader,而InputStreamReader则继承了抽象类Reader。

相关方法:

  1. 构造器:new FileReader(String/File);
  2. read():每次读取单个字符,返回该字符(char和int能自动转换),若到文件末尾返回-1;
  3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,若到文件末尾返回-1;

相关API:

  1. new String(char[]):将char[]转换成字符串;
  2. new String(char[], off, len):将char[]的指定部分转换成String。

案例:

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) {

    }

    @Test
    public void read_1(){ // 一次读取单个字符
        FileReader fr = null;
        int len = 0;
        String filePath = "e:\\self_study\\NoteBook\\Java\\story.txt";
        try {
            fr = new FileReader(filePath);
            while((len = fr.read()) != -1){
                System.out.print((char)len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void read_2(){ // 一次读取多个字符
        FileReader fr = null;
        int len = 0;
        char[] buf = new char[8];
        String filePath = "e:\\self_study\\NoteBook\\Java\\story.txt";
        try {
            fr = new FileReader(filePath);
            while((len = fr.read(buf)) != -1){
                System.out.print(new String(buf, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
}

FileWriter:

直接父类是OutStreamWriter,OutputStreamWriter继承了抽象类Writer。

相关方法:

  1. 构造器:new FileWriter(String/File)——覆盖模式,相当于光标在文件开头;
  2. 构造器:new FileWriter(String/File, true)——添加模式,相当于光标在文件末尾;
  3. write(int):写入单个字符;
  4. write(char[]):写入指定数组;
  5. write(char[], off ,len):写入指定数组的指定部分;
  6. write(String):写入整个字符串;
  7. write(String,off,len):写入指定字符串的指定部分。

相关API:

String类:toCharArray——将String转换为Char[]

在我们使用过FileWriter后,必须要关闭(close)或刷新(flush),否则无法写入指定文件中。

案例:

import org.junit.jupiter.api.Test;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriter_ {
    public static void main(String[] args) {

    }

    @Test
    public void write_1() {
        String dstPath = "E:\\self_study\\NoteBook\\Java\\write_1.txt";
        String wirte = "风雨之后,总见彩虹!";
        FileWriter fw = null;
        try {
            fw = new FileWriter(dstPath);
            fw.write(wirte);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void write_2() {
        String dstPath = "E:\\self_study\\NoteBook\\Java\\write_1.txt";
        String wirte = "风雨之后,总见彩虹!";
        FileWriter fw = null;
        try {
            fw = new FileWriter(dstPath);
            fw.write(wirte.toCharArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


节点流和处理流:

基本介绍:

  1. 节点流:可以从一个特定的数据源读写数据,如 FileReader、FileWriter;(专人做专事。)
  2. 处理流(包装流):其是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter(其不像节点,比方说FileReader只能读取文件,但是BufferedReader却能够读取文件、数组等等!因为其内部有个属性的类型为顶层的抽象类,所以可以接受属于其的众多的子类,即封装一个节点流)。
    1. 这种模式就叫做修饰器模式

节点流和处理流的区别和联系:

  1. 节点流是底层流/低级流(不是说它不好),直接跟数据源相连接;

  2. 处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出;

  3. 处理流(包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连。

    public abstract class Reader_ { // 抽象类
        public abstract void read();
    }
    
    /**
     * Filereader_ 和 StringReader_ 可以看作就是节点流
     */
    class Filereader_ extends Reader_ { // 对文件进行读取操作
        public void read(){
            System.out.println("Reading file");
        }
    }
    
    class StringReader_ extends Reader_ { // 对字符串进行读取读取
        public void read(){
            System.out.println("read String");
        }
    }
    
    /**
     * 下面写一个处理流:
     */
    
    class BufferedReader_ extends Reader_ {
        private Reader_ reader; // 有一个私有属性是Reader_类型
        public BufferedReader_(Reader_ reader) {
            this.reader = reader;
        }
    
        public void read(){
            this.reader.read();
        }
    }
    
    
    public class Test {
        public static void main(String[] args) {
            // 这里我一开始有点迷糊,后来发现new StringReader_()只是作为参数传入了 BufferedReader
            // 其运行类型还是BufferedReader_哦!
            BufferedReader_ bufferedReader = new BufferedReader_(new StringReader_());
            bufferedReader.read(); 
        }
    }
    

处理流的功能主要体现在以下两个方面:

  1. 性能的提高:主要以增加缓冲的方式来提高输入输出的效率;
  2. 操作更加便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便。

处理流——BufferedReader和BufferedWriter:

  • BufferedReader 和 BufferedWriter 属于字符流,是按照字符来读取数据的;
  • 关闭处理流,只需要关闭外层流即可,不用再关闭我们包装的节点流(实际上真正读取的仍然是节点流,处理流只是做了一个包装)。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReader_1 {
    public static void main(String[] args) throws Exception {
        String filePath = "d:\\b.txt";
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = br.readLine()) != null) { // readline会读取完整的一行,当读到文件末尾时,返回空
            System.out.println(line);
        }
        br.close();
    }
}

package com.jiangxian.buffered;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 * 演示BufferedWriter的使用
 */

public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\news2.txt";
        BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
        // 若想要追加,在节点流的构造器中加入true即可。
        bw.write("hello,韩顺平教育!");
        // 建议若后续还有文本时,建议插入换行
        bw.newLine(); // 这就是插入一个换行,且会根据当前系统决定换行符是什么
        bw.close();
    }
}

拷贝:

package com.jiangxian.buffered;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Copy {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("e:\\news2.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("e:\\news3.txt"));
        String line;
        while((line = br.readLine()) != null){
            bw.write(line);
            bw.newLine();
        }
        br.close();
        bw.close();
    }
}

处理流——BufferedInputStream和BufferedOutputStream:

  • BufferedInputStream:其是字节流,在创建 BufferedInputStream 时,会创建一个内部缓冲区数组。
  • BufferedOutputStream:其是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

案例:

package com.jiangxian.buffered;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */


public class Copy_2 {
    public static void main(String[] args) throws IOException {
        String srcPath = "e:\\hello1.txt";
        String dstPath = "e:\\hello2.txt";
        int res = 0;
        byte[] buf = new byte[8];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstPath));
        while((res = bis.read(buf)) != -1){
            bos.write(buf, 0, res);
        }
        bis.close();
        bos.close();
    }
}

对象流——ObjectInputStream和ObjectOutputStream:

为什么要有:

在保存文件的时候,希望把数据的类型保存下来(比如我们保存的100到底是int类型还是String类型呢),所以其需要能够保存值和数据类型

介绍:

  • 功能:提供了对基本类型或对象类型的序列化和反序列化的方法;
  • ObjectInputStream:提供序列化功能;(在保存数据时,保存数据的值和数据类型)
  • ObjectOutputStream:提供反序列化功能。(在恢复数据时,恢复数据的值和数据类型)
  • 若我们想要让某个类支持序列化机制,则必须让其类是可序列化的,为了让这个类是可序列化的,该类必须实现以下两个接口之一:
    • Serializable——标记接口(仅做标记,没有任何方法)推荐
    • Externalizable——该接口有方法需要实现,因此一般推荐使用上面的。

案例:

package com.jiangxian.object_;

import java.io.Serializable;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Dog implements Serializable {
    private String name;
    private int age;
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

package com.jiangxian.object_;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class ObjectOutStream_ {
    public static void main(String[] args) throws IOException {
        // 序列化后,保存的文件格式,不是存放文本,而是按照他的格式来保存
        String filePath = "e:\\data.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        // 序列化数据到 e:\data.dat
        oos.writeInt(100); // 此处发生了自动装箱,int -> Integer(实现了Serializable)
        oos.writeBoolean(true); // boolean -> Boolean(实现了Serializable)
        oos.writeChar('a'); // char -> Character(实现了Serializable)
        oos.writeDouble(3.14); // double -> Double
        oos.writeUTF("江弦凤歌"); // String
        // 保存一个Dog对象
        oos.writeObject(new Dog("旺财", 5));

        oos.close();
        System.out.println("序列化保存文件完成。");
    }
}


package com.jiangxian.InputStream_;


import com.jiangxian.object_.Dog;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 指定反序列化的文件
        String filePath = "e:\\data.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        // 读取
        // 1.读取(反序列化)的顺序需要和保存(序列化)数据一致
        // 2.否则会报异常

        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        Object dog = ois.readObject(); // 底层 Object -> Dog,需要抛出异常
        // dog的编译类型是Object,运行类型为Dog
        System.out.println("运行类型:" + dog.getClass());
        System.out.println("dog信息 = " + dog);

        // 特别重要的细节:
        // 1. 若我们希望调用Dog的方法,我们需要向下转型,但我们发现,此时我们没有这个类
        // 2. 所以我们需要引入这个类。
        Dog dog1 = (Dog) dog;

        ois.close();
    }
}


注意事项和处理细节:

  1. 读写顺序要一致;
  2. 要求实现序列化或反序列化的对象,需要实现Serializable;
  3. 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性;
  4. 序列化对象时,默认将里面所有属性都进行序列化,但除了static 或 transient 修饰的成员(这两个是不会序列化的,及存储的内容中没有这两种信息,要是重写过toString,这两个成员的部分会是null);
  5. 序列化对象,要求在里面的属性的类型也都要实现Serializable接口(除了static 和 transient修饰的)
  6. 序列化具有可继承性,要是某类已经实现了可序列化,其子类都可以实现序列化。

标准输入输出流:

类型默认设备
System.inInputStream键盘
System.outOutputStream显示器
package com.jiangxian.standard_;

import java.util.Scanner;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class InputAndOutput {
    public static void main(String[] args) {
        // System.in:
        // 1.编译类型:InputStream
        // 2.运行类型:BufferedInputStream
        // 表示标准输入,就是键盘
        System.out.println(System.in.getClass());
        
        // System.out:
        // 1.编译类型:PrintStream
        // 2.运行类型: PrintStream
        // 表示标准输出,就是我们的显示器
        System.out.println(System.out.getClass());
        
        Scanner sc = new Scanner(System.in);
    }
}

转换流——InputStreamReader 和 OutputStreamWriter:

作用:将字节流转换成字符流。

为什么需要转换流呢?

因为我们Java中使用的编码是UTF-8,但是又可能我们的文件并不是UTF-8的格式,而我们的字节流是可以设置文件编码格式的,然后再将我们的字节流转换成字符流,我们就解决了我们的文件编码问题。

介绍:

  1. InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流);
    • 构造器:InputStreamReader(InputStream, Charset);——传入一个字节流和编码格式
  2. OutputStreamWriter:Writer的子类,可以将OutputStream(字节流)包装成Writer(字符流);
    • 构造器:OutputStreamReader(OutputStream, Charset);——传入一个字节流和编码格式
  3. 当处理纯文本文件的时候,若使用字符流效率更高,并且可以有效地解决中文问题,所以建议将字节流转换成字符流;
  4. 可以在使用时指定编码格式(UTF-8,gbk等等)。

案例:

package com.jiangxian.transformation_;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 * 中文乱码问题
 */
public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("E:\\self_study\\NoteBook\\Java\\story.txt");
        InputStreamReader isr = new InputStreamReader(fis,"gbk");
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
}

package com.jiangxian.transformation_;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Output_ {
    public static void main(String[] args) throws Exception {
        String filePath = "E:\\self_study\\NoteBook\\Java\\story.txt";
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                                                new FileOutputStream(filePath,true),"gbk"));
        bw.write("庙里有个老和尚");
        bw.newLine();
        bw.close();
    }
}

打印流——PrintStream 和 PrintWriter:

打印流只有输出流没有输入流。

  • PrintStream:继承了FilterOutputStream,是字节流。

    package com.jiangxian.printstream_;
    
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    
    /**
     * @author JiangXian~
     * @version 1.0
     * 演示PrintStream,字节打印流
     */
    public class PrintStream_ {
        public static void main(String[] args) throws Exception {
            // 经典用法,在默认情况下,打印到的位置是标准输出——屏幕
            /*
            public void print(String s) {
                if (s == null) {
                    s = "null";
                }
                write(s);
            }
             */
            PrintStream out = System.out;
            out.print("Hello World");
            // print的底层使用的是write,所以我们可以直接使用write来代替print
            out.print("\nJiangXian");
            out.close();
    
            // 我们可以修改打印流输出的位置/设备
            // 现在我们修改到了story.txt
            System.setOut(new PrintStream("E:\\self_study\\NoteBook\\Java\\story.txt"));
            System.out.println("hello,JiangXian!");
        }
    }
    
    
  • PrintWriter:继承了Writer,是字符流。

    package com.jiangxian.printwriter_;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * @author JiangXian~
     * @version 1.0
     */
    public class PrintWriter_ {
        public static void main(String[] args) throws IOException {
            // 我们可以根据自己的需求调整位置
            // PrintWriter printWriter = new PrintWriter(System.out);
            PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
            printWriter.print("Hello World");
            printWriter.close();
        }
    }
    
    

Properties类:

在集合中讲过(Map的子类)~但是没有提及主要的应用。

看一个需求:

如下一个配置文件:mysql.properties

  • ip = 192.168.0.13;
  • user = root;
  • pwd = 12345。

请问编程读取ip、user 和 pwd的值是多少?

配置文件是我们程序需要读取的,或者是我们的程序对配置文件进行了修改需要写入的。

传统方法:

package com.jiangxian.properties_;

import java.io.*;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Properties01 {
    public static void main(String[] args) throws Exception {
        // 读取mysql.properties文件,并获取相关的信息
        BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties")); // 这里写的是相对路径,src为根目录
        String line;
        while ((line = br.readLine()) != null) {
            String[] str = line.split("="); // 以'='号为界分割为两个String数组
            System.out.println(str[0] + "值是:" + str[1]);
        }
        br.close();
    }
}

传统方案可以解决,但是不是特别方便,我们需要遍历出来,然后判断是不是我们要的值再输出(代码只实现了遍历哦)。

基本介绍:

  1. 专门用于读写配置文件的集合类;
  2. 配置文件的格式:键=值;
  3. 键值对之间不要有空格,值不需要使用引号括起来,默认是String

常见方法:

  • load:加载配置文件的键值对到Properties对象;
  • list:将数据显示到指定设备/流对象;
  • getProperties(key):根据键获取值;
  • setProperties(key, value):设置键值对到Properties对象;
  • store:将Properties中的键值对存储到配置文件中(若已经存在,则覆盖),在idea中,保存信息到配置文件,若含有中文,会存储为unicode码。

案例:

读取:

package com.jiangxian.properties_;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Properties;

/**
 * @author JiangXian~
 * @version 1.0
 * 使用Properties类来读取文件
 */
public class Properties02 {
    public static void main(String[] args) throws Exception {
        // 1.创建对象
        Properties prop = new Properties();
        // 2.load加载文件
        prop.load(new FileReader("src\\mysql.properties"));
        // 3.list显示到屏幕
        prop.list(System.out);
        // 4.根据key获取对应的值
        System.out.println("用户名:" + prop.getProperty("user"));
    }
}

添加:

package com.jiangxian.properties_;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Properties03 {
    public static void main(String[] args) throws IOException {
        // 使用Properties 类来创建配置文件,修改配置文件内容
        Properties prop = new Properties();

        // 创建键值对:
        // 若该文件没有,就创建,有就是覆盖。
        prop.setProperty("charset","utf8");
        prop.setProperty("user","汤姆");
        prop.setProperty("password","123456");

        // 将键值对存储到文件中即可,若你使用Writer存储,会出现乱码,因为你传进去的是Utf-8,将文件格式设置下也能正常显示汉字了
        // null代表什么呢?代表一个注释
        prop.store(new FileOutputStream("src\\mysql2.properties"), null);
        System.out.println("创建配置文件成功!");
    }
}

ngxian.properties_;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Properties;

/**

  • @author JiangXian~
  • @version 1.0
  • 使用Properties类来读取文件
    */
    public class Properties02 {
    public static void main(String[] args) throws Exception {
    // 1.创建对象
    Properties prop = new Properties();
    // 2.load加载文件
    prop.load(new FileReader(“src\mysql.properties”));
    // 3.list显示到屏幕
    prop.list(System.out);
    // 4.根据key获取对应的值
    System.out.println(“用户名:” + prop.getProperty(“user”));
    }
    }



### 添加:

```java
package com.jiangxian.properties_;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @author JiangXian~
 * @version 1.0
 */
public class Properties03 {
    public static void main(String[] args) throws IOException {
        // 使用Properties 类来创建配置文件,修改配置文件内容
        Properties prop = new Properties();

        // 创建键值对:
        // 若该文件没有,就创建,有就是覆盖。
        prop.setProperty("charset","utf8");
        prop.setProperty("user","汤姆");
        prop.setProperty("password","123456");

        // 将键值对存储到文件中即可,若你使用Writer存储,会出现乱码,因为你传进去的是Utf-8,将文件格式设置下也能正常显示汉字了
        // null代表什么呢?代表一个注释
        prop.store(new FileOutputStream("src\\mysql2.properties"), null);
        System.out.println("创建配置文件成功!");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江弦凤歌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值