Java input / output stream

Posted by John_wilson on Sat, 15 Jan 2022 14:05:28 +0100

catalogue

1, Introduction:

2, File class:

2, Absolute and relative paths:

3, Byte stream:

1. Introduction:

2. File input stream:

3. File output stream:

IV. buffer flow:

5, Character stream:

1. Introduction:

2. Byte character conversion stream:

3. Character buffer stream:

Vi. object serialization and deserialization:

1. Introduction:

2. Steps:

3. Two categories are involved:

VII. Comprehensive case: Player

All belong to Java IO package

1, Introduction:

  • The output is a write operation and the input is a read operation.
  • A stream is a channel through which a series of flowing characters send information in a first in first out manner.

2, File class:

  • In Java, use Java io. The file class operates on files.
Common methods of File class
methodexplain
File(File parent,String child)(construction method) indicates which directory or File to operate on for the File object
File(String parthname)(construction method)
File(String parent,String child)(construction method)
File(URI url)(construction method)
boolean canRead()Is it readable
boolean canWrite()Is it writable
boolean exists()Does it exist
String getName()Get name
boolean isDirectory()Is it a directory
boolean isFile()Is it a file
boolean mkdir()Create directory
boolean mkdirs()Create multi-level directory

Example:

package com.file;

import java.io.File;
import java.io.IOException;

public class File1 {

	public static void main(String[] args) {
		//Create File object
		//Method 1:
		File file1=new File("C:\\Users\\dell\\Desktop\\file\\io\\2.txt");  //Pay attention to the writing of escape characters
		//Method 2:
		File file2=new File("C:\\Users\\dell\\Desktop", "file\\io\\1.txt");  //Divide the path into two parts
		//Method 3:
		File file3=new File("C:\\Users\\dell\\Desktop");
		File file4=new File(file3, "file\\io\\1.txt");
		//Determine whether the file is a directory or a file
		System.out.println("Is it a directory?"+file1.isDirectory());
		System.out.println("Is it a file?"+file1.isFile());
		System.out.println("Is it a file?"+file2.isFile());
		System.out.println("Is it a file?"+file4.isFile());
		//create a file
		File file5=new File("C:\\Users\\dell\\Desktop\\file\\set", "a");
		if (!file5.exists()) {
			file5.mkdir();
		}
		//Create a multi-level directory under C:\Users\dell\Desktop\file\set: a\b.
		File file6=new File("C:\\Users\\dell\\Desktop\\file\\set", "a\\b");
		file6.mkdirs();
		//create a file
		if (!file1.exists()) {
			try {
				file1.createNewFile();  //Calling this method requires an exception to be caught
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

2, Absolute and relative paths:

  • Absolute path: the path starting from the drive letter.
  • Relative path: the path starting from the current path.
  • .. \ returns a level up directory

Example:

package com.file;

import java.io.File;
import java.io.IOException;

public class File2 {

	public static void main(String[] args) {
		File f=new File("A\\m.txt");
		try {
			f.createNewFile();
			//Is it an absolute path
			System.out.println(f.isAbsolute());
			//Get relative path
			System.out.println(f.getPath());
			//Get absolute path
			System.out.println(f.getAbsolutePath());
			//Get file name
			System.out.println(f.getName());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Note: location of files generated in Ecipse:

3, Byte stream:

1. Introduction:

  • It is divided into byte input stream InputStream (reading data from the input device) and byte output stream OutputStream (writing data to the output device).
  • Class structure:

2. File input stream:

  • Get input bytes from a file in the file system.
  • Used to read an original byte stream such as image data.
Common methods of FileInputStream class
methodexplain
FileInputStream(File file)(construction method)
FileInputStream(FileDescriptor fd0bj)(construction method) use file descriptors to create objects
FileInputStream(String name)(construction method)
public int read(int b)Read 1 data byte from input stream
public int read(byte[] b)Read up to b.length bytes of data into a byte array from the input stream
public int read(byte[] b,int off,int len)Read up to len bytes of data into the byte array from the input stream. off is the offset (= 0, i.e. read from scratch), and Len is the data length
public void close()Close this file input stream and all system resources associated with this stream

The return value of int type of read() method is - 1, indicating that it has been read to the end of the file! It is a sign to judge whether the file has been read.

Example A:

First create a new txt file in the project (the content is: Hello,Isebal!):

package com.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class File3 {

	public static void main(String[] args) {
		try {
			FileInputStream fileInputStream = new FileInputStream("A.txt");
			int n = 0;
			while ((n = fileInputStream.read()) != -1) {
				System.out.print((char) n); // Be careful to cast to character type
			}
			fileInputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) { // Note that this exception is written later, because FileNotFoundException is its subclass and will be overwritten.
			e.printStackTrace();
		}
	}
}

Example B:

package com.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class File4 {

	public static void main(String[] args) {
		try {
			FileInputStream f1 = new FileInputStream("A.txt");
			FileInputStream f2 = new FileInputStream("A.txt");
			byte[] a = new byte[100];
			byte[] b = new byte[100];
			f1.read(a);
			System.out.println(new String(a));
			f2.read(b, 0, 5);
			System.out.println(new String(b));
			f1.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) { // Note that this exception is written later, because FileNotFoundException is its subclass and will be overwritten.
			e.printStackTrace();
		}
	}
}

3. File output stream:

  • Write data into a file.
methodexplain
FileOutputStream(File file)(construction method)
FileOutputStream(File file,boolean append)(constructor) append data at the end of the file when append is true
FileOutputStream(FileDescriptor fd0bj)(construction method)
FileOutputStream(String name)(construction method)
public void write(int b)Writes the specified bytes of the output stream to this file
public void write(byte[] b)Writes b.length bytes from the specified byte array to the output stream of this file
public void write(int b)(byte[] b,int off,int len)Writes len bytes from the offset off in the specified byte array to this file output stream
public void close()Close this file input stream and all system resources associated with this stream

Example A:

package com.file;

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

public class FileOutPut {

	public static void main(String[] args) {
		FileOutputStream fileOutputStream; // The stream declaration is written outside
		FileInputStream fileInputStream;
		try {
			fileOutputStream = new FileOutputStream("A.txt");  //A
			fileOutputStream.write(50);
			fileOutputStream.write('a'); // Character and integer types can be converted to each other
			fileInputStream = new FileInputStream("A.txt");
			System.out.println(fileInputStream.read()); // Read in the order of writing and sending, read 50
			System.out.println((char) fileInputStream.read()); // Read a
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

If the parameter 2: true is added to the method at A, the file sending changes as follows: it is not overwritten, but appended later.

Example B: copy of file

package com.file;

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

public class FileCopy {

	public static void main(String[] args) {
		// File copy
		try {
			FileInputStream file1 = new FileInputStream("jing.PNG");
			FileOutputStream file2 = new FileOutputStream("jingxx.PNG");
			int n = 0;
			byte[] b = new byte[1024];
			while ((n = file1.read(b)) != -1) {
				file2.write(b);
			}
			file1.close();
			file2.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Note: it is found that the copied file is always 1kb larger than the original file. Solution: add two parameters to the write() method: write(b,0,n). N represents the number of bytes in the byte array actually read to ensure the consistent size of the two files.

IV. buffer flow:

  • It includes BufferedInputStream and BufferedOutputStream.
  • Reading data directly from memory is faster.
  • BufferedInputStream is used in combination with FileInputStream. The process of reading a file is as follows: FileInputStream reads the data from the data source. At this time, it is not directly read into the file for reception, but through a buffer stream. Use byte array to store buffered data.

Common methods of buffering input streams
methodexplain
BufferedInputStream(inputStream in)The (constructor) parameter can be a subclass of any inputStream
BufferedInputStream(inputStream in,int size)(construction method) specifies the buffer size

Common methods of buffering output streams
methodexplain
BufferedOutputStream(OutputStream in)The (constructor) parameter can be a subclass of any inputStream
BufferedOutputStream(OutputStream in,int size)(construction method) specifies the buffer size
void flush()Empty buffer

If the buffer is full, the write operation is performed automatically. If the cache is not full, the write() method will not be triggered to write the data to the file. Therefore, when the buffer is not enough, you need to call the flush() method to forcibly empty the buffer.

5, Character stream:

1. Introduction:

  • It is divided into character input stream Reader and character output stream Writer.
  • Class structure:

  • Difference from byte input / output stream: different purposes. Byte input / output stream reads and writes data in binary format.

2. Byte character conversion stream:

  • It is divided into InputStreamReader and OutputStreamWriter.
Main methods of InputStreamReader class
methodexplain
InputStreamReader(InputStream in)(construction method)
InputStreamReader(InputStream in, Charset cs)(construction method) codes can be set
InputStreamReader(InputStream in, CharsetDecoder dec)(construction method) codes can be set
InputStreamReader(InputStream in, String charsetName)(construction method)
String getEncoding()Get character encoding
int read()
int read(char[] cbuf, int offset, int length)
boolean ready()Determine whether the stream is ready to read

Main methods of OutputStreamWriter class
methodexplain
OutputStreamWriter( OutputStream  out)(construction method)
OutputStreamWriter( OutputStream out, Charset cs)(construction method) codes can be set
 OutputStreamWriter( OutputStream  out, CharsetEncoder enc)(construction method) codes can be set
 OutputStreamWriter( OutputStream  out, String charsetName)(construction method)
void write(int c)
void write(char[] cbuf, int off, int len)
void write(String str, int off,int len)
package com.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Reader {

	public static void main(String[] args) {
		try {
			FileInputStream fis=new FileInputStream("A.txt");
			//Connect FileInputStream with InputStreamReader: take fis as the parameter of InputStreamReader.
			InputStreamReader isr=new InputStreamReader(fis);  
			FileOutputStream fos=new FileOutputStream("AA.txt");
			OutputStreamWriter osw=new OutputStreamWriter(fos);
			int n=0;
			char[]c=new char[10];  //Note that this is a read character array, not a byte array.
			//Method 1:
//			while((n=isr.read())!=-1) {
//				System.out.print((char)n);
//			}
			//Method 2:
			while((n=isr.read(c))!=-1) {
				String s=new String(c,0,n);  //The character actually stored in the character array
				System.out.println(s);
				osw.write(c, 0, n);
				osw.flush();
			}
			fis.close();
			isr.close();
			fos.close();
			osw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Note: the codes of reading and writing data should be consistent, otherwise Chinese garbled code will occur.

3. Character buffer stream:

  • Including BufferedReader and BufferedWriter.
Main methods of BufferedReader
methodexplain
BufferedReader(Reader in)(construction method)
BufferedReader(Reader in, int sz)(construction method) number of custom characters
int read()
int read(char[] cbuf,int off, int len)
String readLine()Read one line (with / r or / n as newline flag)

Common methods of BufferedWriter class
methodexplain
BufferedWriter(Writer out)(construction method)
BufferedWriter(Writer out, int sz)(construction method) number of custom characters
void write(int c)
void write(char[] cbuf,int off, int len)
void write(String s,int off,int len)
void newLine()Write a line separator

Vi. object serialization and deserialization:

1. Introduction:

  • Serialization: the process of converting Java objects into byte sequences (that is, the process of writing objects).
  • Deserialization: the process of restoring a byte sequence to a Java object (that is, the process of reading an object).

2. Steps:

  • Create a class that inherits the Serializable interface.
  • Create an object.
  • Writes objects to a file.
  • Read object information from file.

3. Two categories are involved:

  • Object input stream ObjectInputStream and object output stream ObjectOutputStream.
Main methods of ObjectInputStream class
cexplain
ObjectOutputStream()(construction method)
ObjectOutputStream(OutputStream out)(construction method)
void writeObject(Object obj)Write object

Main methods of ObjectOutputStream class

Method description ObjectInputStream() (construction method) ObjectInputStream(InputStream out) (construction method) String readObject(Object obj) reads the data written by writeObject() and uses it with it

Example:

package com.serial;

import java.io.Serializable;

public class Goods implements Serializable {
	private String id;
	private String name;
	private double price;

	public Goods(String id, String name, double price) {
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Commodity information[No.:" + id + ",name:" + name + ",Price:" + price + "]";
	}
}
package com.serial;

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

public class GoodeTest {

	public static void main(String[] args) {
		Goods goods1 = new Goods("01", "computer", 3000);
		try {
			FileOutputStream fos = new FileOutputStream("A.txt");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			FileInputStream fis = new FileInputStream("A.txt");
			ObjectInputStream ois = new ObjectInputStream(fis);
			// Write the Goods object information to the file
			oos.writeObject(goods1);
			oos.writeBoolean(true);
			oos.flush();
			// Read object information
			try {
				Goods goods2 = (Goods) ois.readObject();
				System.out.println(goods2);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			System.out.println(ois.readBoolean()); // Note that the order of reading should be consistent with the order of writing.
			fos.close();
			fis.close();
			oos.close();
			ois.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The file A.txt is still garbled.

 

VII. Comprehensive case: Player

Topics: Java