InputStream/OutputStream and Reader/Writer concepts in JAVA

learning target:

  • Master the concepts of InputStream/OutputStream and Reader/Writer in JAVA

Learning Content:

InputStream corresponds to Reader
OutputStream corresponds to Writer
Input corresponds to read operation
Output corresponds to write operation

The concept of all this is the concept of memory relative to the file.
If the flow of data is memory -> file, the corresponding operation is OutputStream or Writer.
If the flow of data is file->memory, the corresponding operation is InputStream or Reader.


Code display:

package com.it;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectInputStreamDemo {
    
    
	public static void main(String[] args) {
    
    
		String s = "Hello World";// 定义一个字符串
		byte[] b = {
    
     'e', 'x', 'a', 'm', 'p', 'l', 'e' };// 定义一个字符数组
		try {
    
    
			// 创建一个新文件和一个输出流
			FileOutputStream out = new FileOutputStream("test.txt");
			ObjectOutputStream oout = new ObjectOutputStream(out);

			// 在文件里面写点东西
			oout.writeObject(s);
			oout.writeObject(b);
			oout.flush();
			
			// 为我们之前创建的文件创建一个输入流。
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

			// 读取并打印对象,并将其转换为字符串。
			System.out.println("" + (String) ois.readObject());// 输出“Hello World”

			// 读取并打印对象,并将其转换为字符串。
			byte[] read = (byte[]) ois.readObject();
			String s2 = new String(read);
			System.out.println("" + s2);// 输出“example”

		} catch (Exception ex) {
    
    
			ex.printStackTrace();
		}
	}
}

The code has clearly shown how the object input and output streams operate.

Output result:
insert image description here


Guess you like

Origin blog.csdn.net/weixin_45345143/article/details/128651847