Java : IO 流

Stream input and output:

  • Input: refers to importing data into the memory
  • Output: Refers to writing data from memory

Classification of flow:
Insert picture description here

1. FileInputStream (file byte input stream):

Construction method:

  • FileInputStream(File file): Pass in the File file to create a stream object

  • FileInputStream(String name): Pass in a string file address to create an object

Common methods:

  • available(): returns the number of remaining readable bytes
  • read(): Read one byte of data and return the value of the next byte
  • read(byte[] b): read b.length bytes from the input stream to the array
  • skip(long n): skip the data in the n-byte input stream
	public static void main(String[] args) {
    
    
		FileInputStream fis = null ;
		try {
    
    
			fis = new  FileInputStream("相对/绝对路径");
			int i1 =  fis.read();
			 System.out.println((char)i1);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}finally{
    
    
			try {
    
    
				if(fis != null){
    
    
					fis.close();
				}
			} catch (IOException e) {
    
    
				e.printStackTrace();
			}
		}
	}

2. FileOutputStream (file byte output stream):

Construction method :

  • FileOutputStream(String): output the contents of the stream to the specified file, and will overwrite the contents of the original file
  • FileOutputStream(String name, boolean append): If the second parameter is true, output the content to the specified file and append data to the original file

Member method:

  • write(int i): write out integer data
  • write(byte[] b): Write out the byte array. If you want to output the string, you can use the getBytes() method in the string to convert the string to a byte array
  • flush(): flush the cache and force the buffer to be written out to avoid data omissions
	public static void main(String[] args) throws IOException {
    
    
		// 创建输出流对象,数据在文件中追加
		FileOutputStream fos = new FileOutputStream("D:/123.txt", true);
		//输出a-z
		for (int i = 0; i < 26; i++) {
    
    
			fos.write(i + 97);
		}

		// 写出字符串
		String str = "Hello world";
		byte[] bytes = str.getBytes();//将字符串转换为字节数组
		fos.write(bytes);

		// 刷缓存,避免数据遗漏
		fos.flush();
		// 关闭流
		fos.close();
	}

3. FileReader (file character input stream)

The character input stream reads one character at a time, which is 2 bytes, and the unicode encoding is also 2 bytes. Character input streams are generally used to read plain text files, such as compressed packages, pictures, etc. or use byte streams

Construction method:

  • read(): Read one character, return the next character data, and return -1 when it reaches the end of the file
  • read(char[] c): Read a character array, return the number of characters read, and return -1 when the end of the file is reached
	public static void main(String[] args) {
    
    
		try(
				FileReader fr = new FileReader("D:/test.java");
				) {
    
    
			char[] chars = new char[512];
			int tmp = 0;
			while((tmp = fr.read(chars)) != -1){
    
    
				//防止重复数据,只把字节数中本次读取的数据转换成字符串即可
				System.out.print(new String(chars,0,tmp));
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

4、FileWriter

The byte output stream is basically the same, but it can write strings

public static void main(String[] args) {
    
    
		try (
				FileWriter fw = new FileWriter("D:/123.txt");
				){
    
    
			
			//写出字符串
			fw.write("你好吗\n");
			
			//写出字符数组
			char[] chars = {
    
    'a','b','c','d'};
			fw.write(chars);
			
			//刷新数组
			fw.flush();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

5. Buffered stream

The buffer stream is a package stream. When creating an object, the parameter passed in is no longer a file address, but a file stream object. If the buffered stream is closed, the corresponding file stream object passed in will also be closed.

缓冲流分为:BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter

Role:

  • Store the data read in each time into a buffer, write once
  • Store the output data in a buffer and write it out at a time

For character manipulation, two new methods are provided

  • readLine(): read a line, the return value is the data of the read line, reach the end of the file, return null
  • newLine(): newline, it is equal to \n

(1)BufferedInputStream:

	public static void main(String[] args) {
    
    
		try(
				// 创建字节输入流
				FileInputStream fis = new FileInputStream("./src/io/FileInputStream_02.java");
				// 创建字节输入缓冲流
				BufferedInputStream bis = new BufferedInputStream(fis);
				) {
    
    
			// 读取下一个字节,到达末尾返回 -1
			System.out.println((char)bis.read());
			// 读取一个数组,返回读取到的长度,到达末尾返回-1
			byte[] bytes = new byte[10];
			//从缓冲流中读取数据,返回读取的字节数
			int temp =bis.read(bytes);
			//避免数据冗余,只将本次读取的数据转换成字符串
			System.out.println(new String(bytes,0,temp));
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		
	}

(2)BufferedOutputStream

	public static void main(String[] args) {
    
    
		try (
				// 创建字节输出流对象
				FileOutputStream fos = new FileOutputStream("D:/123.txt");
				// 创建字节输出缓冲流对象,并把字节输出流传入
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				){
    
    
			// 写出单个
			bos.write(97);
			//写出字符串
			String ss = "dfwefwsefnweifniwdfn";
			byte[] bytes = ss.getBytes();
			bos.write(bytes);
			// 刷缓存
			bos.flush();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

(3)BufferedReader

	public static void main(String[] args) {
    
    
		try (
				// 创建字符输入流
				FileReader fr = new FileReader("./src/io/FileInputStream_02.java");
				// 创建字符输入缓冲流,并把字符输入流传入
				BufferedReader br = new BufferedReader(fr);
				) {
    
    
			// 循环读取
			String tmp = null;
			while( (tmp=br.readLine()) != null ){
    
    
				System.out.println(tmp);
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

(4)BufferedWriter

	public static void main(String[] args) {
    
    
		try (
				FileWriter fw = new  FileWriter("D://123.txt");
				// 创建字符输出缓冲流,并把字符输出流传入 
				BufferedWriter bw = new BufferedWriter(fw);
				){
    
    
			bw.write("你好吗");
			bw.newLine();//换行
			bw.write("你吃了吗");
			bw.flush();// 刷缓存
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

6. InputStreamReader (conversion stream):

Role: Convert byte stream to character stream

	public static void main(String[] args) {
    
    
		try (
				// 创建一个字节输入流对象
				FileInputStream fis = new FileInputStream("./src/io/FileInputStream_02.java");
				// 创建转换流对象,并把字节输入流传入,转换为字符流
				InputStreamReader isr = new InputStreamReader(fis);
				// 创建字符输入缓冲流,把转换流传入
				BufferedReader br = new BufferedReader(isr);
				){
    
    
			String tmp = br.readLine();
			System.out.println(tmp);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}

7. PrintStream (printing stream):

	public static void main(String[] args) throws FileNotFoundException {
    
    
		// 创建输出流
		FileOutputStream fos = new FileOutputStream("D:/log.txt");
		// 创建打印流对象,并传入输出流对象
		PrintStream ps = new PrintStream(fos);
		// 调用打印方法,打印到输出流指定路径
		ps.println("日志系统");

		//设置System中的out
		//再次打印的话,不会打印在控制台,而是打印在D:/log.txt
		System.setOut(ps);
	}

8. Object flow:

(1) Serialization:

Before talking about object streams, let me talk about serialization. We write programs and create Java objects that exist in memory, but memory cannot store data for a long time. For example, when the computer is shut down, the objects are destroyed. Hard disks can store data persistently, and serialization is the process of converting objects into binary streams to enable data persistence and network transmission. Deserialization is to load the object file in the hard disk into the memory.

For a class in Java to be instantiated, it must implement the Serializable interface. There is no method in the interface, but just a mark for special processing by the compiler.

Set serialVersionUID:

  • If you do not add UID, you need to re-serialize each time you change the User class, otherwise deserialization will report an error
  • Perform version control of serialized objects. Once deserialized, InvalidClassException will be thrown if the version does not correspond to
  • If not specified, a new UID will be automatically generated every time the Java class is changed

Create User class, implement Serializable interface

public class User implements Serializable {
    
    
	
	private static final long serialVersionUID = 1L;
	private String name;
	//使用transient修饰符修饰age属性,则它不会被序列化
	//当反序列化的时候,再访问该属性,就是对应数据类型的默认值
	private transient int age;

	public void m1() {
    
    
		System.out.println("新增m1");
	}
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	public User(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
    
    
		return "User [name=" + name + ", age=" + age + "]";
	}
}

Create a test class to serialize the User object:

public class ObjectOutputStream_ {
    
    
	public static void main(String[] args) {
    
    
		User user = new User("张三", 18);
		try (
				// 创建字节输出流对象
				FileOutputStream fos = new FileOutputStream("D:/user");
				// 创建序列化对象,并把字节输出流传入
				ObjectOutputStream oos = new ObjectOutputStream(fos);) {
    
    
			// 写出对象,保存在应硬盘中
			oos.writeObject(user);
			// 刷缓存,避免遗漏流中数据
			oos.flush();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

Create a test class and deserialize it:

public class ObjectInputStream_ {
    
    
	public static void main(String[] args) {
    
    
		try (
				//创建字节输入流对象
				FileInputStream fis = new FileInputStream("D:/user");
				//创建反序列化对象,传入字节流对象
				ObjectInputStream ois = new ObjectInputStream(fis);
				){
    
    
			// 读取,生成对象,可以正常使用
			User user =(User) ois.readObject(); 
			user.m1();//调用对象的方法,可以正常使用
			System.out.println(user);//打印对象
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

9. Data stream (DataOutputStream and FileInputStream)

Use the data stream to conveniently manipulate the basic data types of the Java language and String data.

According to the type of storage, the writing order and the reading order need to be the same, otherwise the code is garbled

public class DataOutputStream_ {
    
    
	public static void main(String[] args) {
    
    
		try (
				// 创建字节输出流
				FileOutputStream fos = new FileOutputStream("D:/test.txt");
				// 创建数据输出流,并传入字节输出流对象
				DataOutputStream dos = new DataOutputStream(fos);
		) {
    
    
			//写出指定数据类型
			dos.writeByte(1);//写出字节型
			dos.writeInt(3); //写出整型
			dos.writeShort(2);//写出短整型
			dos.writeLong(5);//写出长整型
			dos.writeDouble(5.7);//写出浮点型
			dos.writeUTF("你好吗");//写出字符串型

			// 刷缓存,为了避免遗漏数据
			dos.flush();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}
public class DataInputStream_ {
    
    
	public static void main(String[] args) {
    
    
		try (
				//创建字节输入流对象
				FileInputStream fis = new FileInputStream("D:/test.txt");
				//创建数据输入流对象
				DataInputStream dis = new DataInputStream(fis);
				){
    
    
			// 读取顺序需要和写入顺序一致
			//不然会发生数据错误
			System.out.println(dis.readByte());
			System.out.println(dis.readInt());
			System.out.println(dis.readShort());
			System.out.println(dis.readLong());
			System.out.println(dis.readDouble());
			System.out.println(dis.readUTF());
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/113187947