Java学习路线(19)——IO流(下)

一、缓冲流

1、概念: 一种自带缓冲区的字节流、可提高原始字节流、字符流读写数据的性能。

2、缓冲流高性能原理: 磁盘与内存之间有一块存储区域,当磁盘向内存传输数据时,先传输到缓冲区,当缓冲区满了之后,一起传输给内存中,如图所示。
在这里插入图片描述
3、缓冲流类型

  • BufferedInputStream 字节缓冲输入流
  • BufferedOutputStream 字节缓冲输出流
  • BufferedReader 字符缓冲输入流
  • BufferedWriter 字符缓冲输出流

4、字节缓冲流性能优化原理: 字节缓冲流自带8KB缓冲池,以便我们读取写入数据。

5、创建缓冲流API

构造器 说明
BufferedInputStream(InputStream in) 为指定字节输入流创建缓冲区
BufferedInputStream(InputStream in,int size) 为指定字节输入流创建指定大小的缓冲区
BufferedOutputStream(OutputStream in) 为指定字节输出流创建缓冲区
BufferedOutputStreamStream(OutputStream in,int size) 为指定字节输出流创建指定大小的缓冲区
BufferedReader(Reader in) 为指定字符输入流创建缓冲区
BufferedReader(Reader in,int size) 为指定字符输入流创建指定大小的缓冲区
BufferedWriter=(Writer in) 为指定字符输出流创建缓冲区
BufferedWriterStream(Writer in,int size) 为指定字符输出流创建指定大小的缓冲区

缓冲字符流新增API

方法 说明
String readLine() 读取文本的一行
public class BufferedStreamDemo{
    
    
	public static void main(String[] args) {
    
    
		try(
				/*1、创建字符缓冲输入流*/
				BufferedReader br = new BufferedReader(new FileReader("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\loco.txt"));
				) {
    
    
			while(br.ready()){
    
    
				System.out.println(br.readLine());
			}
			System.out.println("复制完整");
		} catch (IOException e) {
    
    
			throw new RuntimeException(e);
		}
	}
}

二、转换流

1、概念: 由于不同编码会导致读取乱码问题,所以转换流能够转换成指定编码的输入流。

2、类型

  • InputStreamReader 字符输入转换流
  • OutputStreamReader 字符输出转换流

3、获取转换流

构造器 说明
InputStreamReader(InputStream is) 把原始字节流按照代码默认编码转换成字符输入流
InputStreamReader(InputStream is, String charset) 把原始字节流按照指定编码转换成字符输入流
OutputStreamWriter(OutputStream is) 把原始字节流按照代码默认编码转换成字符输出流
OutputStreamReader(OutputStream is, String charset) 把原始字节流按照指定编码转换成字符输出流

三、序列化与反序列化

1、对象序列化的概念: 以内存为基准,把内存中的对象存储到磁盘文件中,称为序列化,反之则为反序列化
2、对象字节IO流:

  • ObjectInputStream

(1)获取输入流

构造器 说明
ObjectInputStream(InputStream out) 把低级字节输入流包装成高级的对象字节输入流

(2)写入输入流

方法 说明
void readObject() 把对象从流中读出

反序列化对象

public class ObjectOutputStreamDemo {
    
    
    public static void main(String[] args) {
    
    
        /*1、空对象*/
        User user = new User();
        try (
                /*2、创建对象字节流*/
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\out.txt"));
        ){
    
    
            user = (User) ois.readObject();
            System.out.println(user);

        } catch (IOException | ClassNotFoundException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

/*打印输出*/
User{
    
    id='9fd3f9ea-2783-4327-bdd3-b10e7683d59a', username='Administrator', password='asfdsgasdfdEW1245EWFC', age=25}
  • ObjectOutputStream

获取输出

构造器 说明
ObjectOutputStream(OutputStream out) 把低级字节输出流包装成高级的对象字节输出流

写入数据

方法 说明
void writeObject(Object obj) 将对象序列化输出至流中

序列化对象

public class ObjectOutputStreamDemo {
    
    
    public static void main(String[] args) {
    
    
        /*1、对象初始化*/
        User user = new User(UUID.randomUUID().toString(),"Administrator","asfdsgasdfdEW1245EWFC",25);
        try (
                /*2、创建对象字节流*/
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\out.txt"));
        ){
    
    
            /*3、写入文件*/
            oos.writeObject(user);
            System.out.println("序列化完成");
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

/*实现Serializable接口才能序列化*/
class User implements Serializable{
    
    
    private String id;
    private String username;
    private String password;
    private int age;

    public User() {
    
    
    }

    public User(String id, String username, String password, int age) {
    
    
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public String getId() {
    
    
        return id;
    }

    public void setId(String id) {
    
    
        this.id = id;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

out.txt

�� sr com.zengoo.logback.User8�b�Xy� I ageL idt Ljava/lang/String;L passwordq ~ L usernameq ~ xp   t $9fd3f9ea-2783-4327-bdd3-b10e7683d59at asfdsgasdfdEW1245EWFCt 
Administrator

注意: 若对象中有属性不希望被序列化,则添加transient关键字声明


四、打印流

1、概念: 打印流实现方便、高效的在文件中写入数据。

2、类型

  • PrintStream(支持字节打印)
构造器 说明
PrintStream(OutputStream out) 打印流直接通向字节输出流管道
PrintStream(File f) 打印流直接通向文件对象
PrintStream(String apth) 打印流直接通向文件路径
方法 说明
void print(E e) 打印任何类型的数据

打印数据到文件示例

public class PrintDemo {
    
    
    public static void main(String[] args) {
    
    
        try(
                /*1、创建打印流*/
                PrintStream printStream = new PrintStream("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\out.txt");
        ) {
    
    
            printStream.println("东临碣石".toCharArray());
            printStream.println("以观沧海".toCharArray());
            printStream.println("水何澹澹".toCharArray());
            printStream.print("山岛竦峙".toCharArray());
            System.out.println("打印完毕");
        } catch (FileNotFoundException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

out.txt

东临碣石
以观沧海
水何澹澹
山岛竦峙
  • PrintWriter(支持字符打印)
构造器 说明
PrintWriter(OutputStream out) 打印流直接通向字节输出流管道
PrintWriter(Writer writer) 打印流直接通向字符输出流管道
PrintWriter(File f) 打印流直接通向文件对象
PrintWriter(String apth) 打印流直接通向文件路径
方法 说明
void print(E e) 打印任何类型的数据

3、输出语句重定向(打印流的应用)

主要用于将控制台打印的语句输出到文件中保存。

PrintStream ps = new PrintStream("文件地址");
System.setOut(ps)

五、Propertis

1、概念: Propertis 意思是 属性,所以它虽然是隶属于集合类,但通常不用它作为集合使用。
2、作用: Propertis代表一个属性文件,可以将自己的键值对信息存入到数据文件中去。
3、Propertis常用API

方法 说明
void load(InputStream inStream) 从输入字节流中读取属性列表(键值对)
void load(Reader reader) 从输入字节流中读取属性列表(键值对)
void store(OutputStream out, String comments) 将此属性列表写入此Propertis列表中,以适用于使用load(InputStream) 方法的格式写入输出字节流
void store(Writer writer, String comments) 将此属性列表写入此Propertis列表中,以适用于使用load(InputStream) 方法的格式写入输出字符流
Object setProperty(String key, String value) 保存键值对(put)
String setProperty(String key) 使用键搜索属性值(get)
Set<String> stringPropertiesNames() 所有键名集合(keySet())

使用Properties示例

public class PropertiesDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        /*创建属性集合*/
        Properties properties = new Properties();
        properties.setProperty("id","123");
        properties.setProperty("username","Admin");
        properties.setProperty("password","avtbhn324t@");
        properties.setProperty("sex","male");
        System.out.println(properties);

        /*保存管道*/
        properties.store(new FileWriter("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\users.properties"),"It's user base-info");
    }
}

/*打印输出*/
{
    
    password=avtbhn324t@, sex=male, id=123, username=Admin}

users.properties

#It's user base-info
password=avtbhn324t@
sex=male
id=123
username=Admin

加载Properties文件

public class PropertiesLoadDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Properties properties = new Properties();
        properties.load(new FileReader("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\users.properties"));
        System.out.println(properties);
    }
}

/*打印输出*/
#It's user base-info
password=avtbhn324t@
sex=male
id=123
username=Admin

获取Properties中的数据

public class PropertiesGet {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Properties properties = new Properties();
        properties.load(new FileReader("D:\\JavaBase\\JavaSEpro\\src\\com\\zengoo\\logback\\users.properties"));
        /*根据键值获取值*/
        System.out.println(properties.getProperty("username"));
        System.out.println(properties.getProperty("password"));
        /*获取所有键名*/
        System.out.println(properties.stringPropertyNames());
    }
}

/*打印输出*/
Admin
avtbhn324t@
[password, sex, id, username]

六、IO框架——commons-io

具体的API查看commons-io的技术文档。

1、概述: commons-io是apache开源基金组织提供的一组有关IO操作的类库,可以提高IO功能开发的效率。

2、主要类

  • FileUtils

常用API

方法 说明
String readFileToString(File file, String encoding) 读取文件中的数据,返回字符串
void copyFile(File srcFile, File destFile) 复制文件
void copyDirectoryToDirectory(File srcFile, File destDir) 复制文件夹
  • IOUtils

3、使用commons-io
(1)下载commons-io-xx.jar
(2)加载到项目中
(3)导包使用

猜你喜欢

转载自blog.csdn.net/Zain_horse/article/details/130958985