Java IO Stream Learning

Keywords: Java encoding Windows

Java IO Stream Learning


  

1 IO Flow Overview

Stream is a sequence of bytes with starting and ending points
_2. Classification of streams:
_input/output stream
_is based on the current program as a reference, if the program reads data from the outside is the input stream, if the program saves data to the outside is the output stream.

_byte stream/character stream
_If the data in the stream is processed in bytes, it is a byte stream, and if the data in the stream is processed in characters, it is a character stream.

_Node Flow/Processing Flow
Reading and writing data directly from the device is the node flow, and the processing flow is the packaging of the node flow.

_IO stream in Java.io package, mainly collates several stream classes related to read and write files. In these stream classes, if the end of Stream word is byte stream, the end of Reader word is character input stream, and the end of Writer is character output stream.

2-byte stream

2.1 Read file content in bytes

/**
 * FileInputStream Class reads file content in bytes
 */
public class Test01 {

	public static void main(String[] args) throws IOException {
		//1) Establish a flow path between the current procedure and the operating documents
		//Specify the file to be operated on through the parameters of the FileInputStream constructor
		FileInputStream fis = new FileInputStream("d:/abc.txt");
		//Current file content: abc
		
		//2) Read the contents of the file. read() can read a byte from the file, and return the byte read to - 1 at the end of the file.
		int cc = fis.read();  	//Read a, return 97
		System.out.println( cc );
		cc = fis.read();		//Read b, return 98
		System.out.println(cc);
		cc = fis.read();		//Read c, return 99
		System.out.println(cc);
		cc = fis.read();		//Speaking of the end of the document, -1
		System.out.println(cc);
		
		//3) Closing of circulation channels
		fis.close();
	}
}

2.2 Loop Read

/**
 * FileInputStream Class reads file contents in bytes	
 */
public class Test02 {

	public static void main(String[] args) throws IOException {
		//1) Establish a flow path between the current procedure and the operating documents
		//Specify the file to be operated on through the parameters of the FileInputStream constructor
		FileInputStream fis = new FileInputStream("d:/abc.txt");
		
		//2) Read the contents of the file. read() can read a byte from the file, and return the byte read to - 1 at the end of the file.
		int cc = fis.read();  	
		//When cc is not - 1, it means that it is not at the end of the file. The byte cc mentioned can be processed and read further.
		while( cc != -1 ){
			//Convert the read byte cc to a character and print it to the screen, because there are only English characters in the current file, one English character takes up one byte.
			System.out.print(  (char)cc  );
			//Continue reading and save the bytes read to cc
			 cc = fis.read();
		}
		//3) Closing of circulation channels
		fis.close();
	}
}
abc
Process finished with exit code 0

2.3 Read file contents in byte arrays

/**
 * Read bytes from files and save them in byte arrays
 *
 */
public class Test03 {

	public static void main(String[] args) throws IOException {
		//1) Establishment of circulation channels
		FileInputStream fis = new FileInputStream("d:/abc.txt");
		//File content: abcdefabcdef
		
		byte [] bytes = new byte[8]; 			//Define a byte array of length 8,
		
		//2) Read the content of the file, save it in the byte array, return the number of bytes read, and return - 1 if read at the end of the file.	
		int len = fis.read(bytes); 		//Read bytes from a file and save them in bytes arrays. The len return value is the read byte array.
		
		System.out.println( len ); 		//8, read the eight bytes of abcdefab from the file
		System.out.println( Arrays.toString(bytes));
		//[97, 98, 99, 100, 101, 102, 97, 98]
		//Converting read byte arrays to string printing
		System.out.println( new  String(bytes , 0 ,len ) );
		
		len = fis.read(bytes); 			//Read the four bytes of cdef in the file	
		System.out.println( len );		//4
		System.out.println( Arrays.toString(bytes) );
		//[99, 100, 101, 102, 101, 102, 97, 98]
		//Convert read 4 bytes to string printing
		System.out.println( new  String(bytes , 0 , len) );
		
	}
}
8
[97, 98, 99, 100, 101, 102, 97, 98]
abcdefab
4
[99, 100, 101, 102, 101, 102, 97, 98]
cdef

Process finished with exit code 0

2.4 Loop Read Byte Array

/**
 * Loop read bytes from files and save them in byte arrays
 */
public class Test04 {

	public static void main(String[] args) throws IOException {
		//1) Establishment of circulation channels
		FileInputStream fis = new FileInputStream("d:/abc.txt");
		
		byte [] bytes = new byte[8]; 			//Define a byte array of length 8,
		
		//2) Read the content of the file, save it in the byte array, return the number of bytes read, and return - 1 if read at the end of the file.	
		int len = fis.read(bytes); 		//Read bytes from a file and save them in bytes arrays. The len return value is the read byte array.
		
		//When len!=-1 does not reach the end of the file, process the bytes read and continue to read down.
		while( len != -1 ){
			//Converting read len bytes to string printing
			System.out.print( new  String(bytes , 0 ,len ) );
			
			//Continue to read down and store the read bytes in the byte array
			len = fis.read(bytes);
		}
		//3) Closing flow
		fis.close();
	}
}
abcdefabcdef
Process finished with exit code 0

Exception Handling of 2.5 IO Flow

/**
 * FileInputStream Exception handling in read files
 *
 */
public class Test05 {

	public static void main(String[] args) {
//		m1(); // Read by byte, exception handling, manual closure of the stream
		m2(); 		//Read an array of bytes at a time, handle exceptions, and automatically close the stream
	}

	private static void m2() {
		//Starting with JDK7, try resource blocks can be automatically closed
		try (		//The try resource block, in which the established circulation channel is automatically closed
				FileInputStream fis = new FileInputStream("d:/abc.txt");
				) {
			byte[] bytes = new byte[1024] ; 	//The length of byte arrays is generally defined as an even multiple of 1024.
			
			int len = fis.read(bytes);
			while( len != -1 ){
				System.out.print( new String(bytes,0,len));
				 len = fis.read(bytes);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void m1() {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("d:/abc.txt");
			
			int cc = fis.read();
			while( cc != -1) {
				System.out.print( (char)cc );
				cc = fis.read();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if ( fis != null ) {
				try {
					fis.close();  //Close the flow and release system resources fairly. 
				} catch (IOException e) {
					e.printStackTrace();
				} 					
			}
		}
				
	}

}

2.6 Write content to a file

/**
 * FileOutputStream Save data in bytes to a file
 */
public class Test06 {

	public static void main(String[] args) throws IOException {
		//1) Establishment and circulation of documents
		//If the file does not exist, the system will create a new file, and if the file already exists, it will overwrite the original content of the file.
//		FileOutputStream fos = new FileOutputStream("d:/def.txt"); Open the file override
		//If the file does not exist, create the file, and if the file already exists, append the newly written content to the end of the file.
		FileOutputStream fos = new FileOutputStream("d:/def.txt" , true );   //By way of additions
		
		//2) Save arrays in bytes to files
		fos.write( 97 );  		//Write one byte at a time
		fos.write(98);
		fos.write(99);
		
		//Write an array of bytes at a time
		byte[] bytes = "hello,abcdefg".getBytes();
		fos.write(bytes);
		
		//Save part of the byte array to a file
		fos.write(bytes, 0, 5); 		//Save 5 bytes from 0 in bytes byte array to file
		
		//3) Closing of circulation channels
		fos.close();
	}
}

2.7 Implementing File Replication

/**
 * File replication in bytes
 *
 */
public class Test07 {

	public static void main(String[] args) {
		String file1 = "F:\\code\\test\\src\\main\\java\\io\\fileinputstream\\Test07.java"	;
		String dest1 = "F:\\test.java";
		copyfile(file1, dest1);

		copyfile2(file1, file1);
	}
	
	//File copy, one array at a time
	public static void copyfile2( String  srcFile,  String destFile) {
		try(
				FileInputStream fis = new FileInputStream(srcFile);
				FileOutputStream fos = new FileOutputStream(destFile);
				) {
			byte [] bytes = new byte[1024];
			int len = fis.read(bytes);
			while( len != -1 ){
				fos.write(bytes, 0, len);
				len = fis.read(bytes);
			}
		} catch (Exception e) {
		}
	}
	
	//Define a method to copy files, copy the contents of srcfile files to destFile files, and copy one byte at a time
	public static void copyfile( String  srcFile,  String destFile) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(srcFile);
			fos = new FileOutputStream(destFile);			
			int cc = fis.read(); 		//Read a byte from the input stream
			//When the byte read is not - 1, the byte cc read is saved in the output stream.
			while( cc != -1 ){
				fos.write(cc);
				cc = fis.read(); 
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if ( fis != null ) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}							
			}
		}
	}
}

3 character stream

FileReader reads the contents of a file in characters
FileWriter saves data to files in character units

Attention:
FileReader/FileWriter can only read and write plain text files
_2)FileReader/FileWrite text file coding should be compatible with current environment coding

3.1 Read File Content

/**
 * FileReader Read file content
 */
public class Test01 {

	public static void main(String[] args) throws IOException {
		//1) Establishment of circulation channels
		FileReader fr = new FileReader("f:/test.java");	//The code of the test07.java file is utf-8
//		FileReader fr = new FileReader("d:/abc.txt"); the //abc.java file code is GBK
		//2) Read the content. read() reads one character at a time, returns the code value of the character, and returns - 1 at the end of the file.
		int cc = fr.read();
		while( cc != -1){
			System.out.print( (char)cc );
			cc = fr.read();
		}
		//3) Closing flow
		fr.close();
	}

}

3.2 Read Character Array

/**
 * Read an array of characters at a time
 */
public class Test02 {

	public static void main(String[] args) {
		try (
				//Establishing a circulation channel in the try resource block will automatically shut down
				FileReader fr = new FileReader("d:/test07.java");
				){
			//Create character arrays
			char [] contents = new char[1024];
			//Read characters from the file and save them in the character array. Return the number of characters read, and return - 1 at the end of the file.
			int len = fr.read(contents);
			while( len != -1 ){
				//Converting read characters to strings
				System.out.print( new String(contents, 0, len ) );
				len = fr.read(contents);
			}			
		} catch (Exception e) {
		}
	}
}

3.3 Write characters to files

/**
 * FileWriter
 *
 */
public class Test03 {

	public static void main(String[] args) {
		FileWriter fw = null;
		try {
			fw = new FileWriter("d:/def.txt"); 		//Open in a covered manner
			//Write one character at a time
			fw.write(97); 		//Code value of characters
			fw.write(30028);
			fw.write('Chinese');			
			//Write an array of characters at a time
			char [] contents = "Hello Hello".toCharArray();
			fw.write(contents);			
			//Write a string at a time
			fw.write("Write a string at a time");			
			//Line wrapping. In Chinese Windows, line wrapping requires two charactersrn
			fw.write("\r\n");			
			//Partial Characters of a Primary Writing Character Array
			fw.write(contents, 0 , 4);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

3.4 Implementing Text Replication

4 Conversion Flow

_1) When the text file encoding is compatible with the current environment encoding, use FileReader/FielWriter to read and write.
_2) When the text file encoding is incompatible with the current environment encoding, use InputStreamReader/OutputStreamWriter
_3) These two stream classes are called conversion stream classes.
_4) InputStream Reader can convert byte stream to character stream
_5) Output Stream Writer can convert character stream to byte stream

public class Test04 {

	public static void main(String[] args) throws IOException {
//		m1(); // Read text files in the specified encoding format
		m2();			//Save data to a file with the specified encoding
	}

	private static void m2() throws IOException {
		//Save the data to the d:/abc.txt file, which is encoded in GBK
		OutputStream out = new FileOutputStream("d:/abc.txt", true);
		//Converts characters to byte streams with the specified encoding
		OutputStreamWriter osw = new OutputStreamWriter(out, "GBK");
		
		osw.write("Current environmental use UTF8 Code, Save data to GBK Documentation");
		
		osw.close();
	}

	private static void m1() throws IOException {
		//The d:/Abc.txt file is GBK-coded. 
		//InputStream is an abstract class that needs to assign subclass objects. FileInputStream inherits InputStream.
//		InputStream in = new FileInputStream("d:/abc.txt");
		FileInputStream in = new FileInputStream("d:/abc.txt");
		//Read the data in the in byte stream with GBK encoding. 
		InputStreamReader isr = new InputStreamReader(in, "GBK");
		
		int cc = isr.read();
		while( cc!=-1){
			System.out.print((char)cc);
			cc = isr.read();
		}
		
		isr.close();
	}

}

4 Buffer Stream

/**
 * BufferedReader/BufferedWriter
 * 	Buffer character stream
 */
public class Test05 {

	public static void main(String[] args) throws IOException {
//		m1(); // Read files using BufferedReader
		m2();		//Use BufferedWriter to save data to files
	}

	private static void m2() throws IOException {
		//Establishing Character Flow Channel
		FileWriter out = new FileWriter("d:/def.txt", true );
		//Buffer character streams
		BufferedWriter bw = new BufferedWriter(out);
		
		//When using buffer streams, arrays are saved in buffers and not immediately in files.
		bw.write("This is data written using a character buffer stream");
		
//		bw.flush(); // Clears the data from the buffer into the file
		bw.close();
	}

	private static void m1() throws IOException {
		//Establishing Character Flow Channel
		Reader in = new FileReader("d:/test07.java");
		//Buffer character streams
		BufferedReader br = new BufferedReader(in);
		
		//You can read one line at a time from the character stream and return null at the end of the file.
		String line = br.readLine();
		while( line != null ){
			System.out.println( line );
			line = br.readLine();
		}
		
		br.close();
	}

}

5 Object Serialization

_serialization
Converting an object to a 01 binary sequence
_Object deserialization:
_Converts a set of 01 binaries to objects

The_ObjectOutputStream class can serialize objects into files, which is simply understood as saving objects into files.
_ObjectInputStream can de-serialize objects, which is simply understood as reading objects from files.

Attention:
__1) The premise of object serialization/deserialization is that the class of object implements Serializable interface.
If the object of a class is to be serialized, in general, a serialized version number field will be added manually in the class.

public class Person implements Serializable {
	String  name;
	int age;
	String gender;

	//Manually add a serial Version UID field to prevent version number inconsistencies during deserialization
	private static final long serialVersionUID = -713246547316498710L;
	
	
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]";
	}
	
}
/**
 * Object serialization
 * 	Using the ObjectOutputStream class
 * 	The premise is that the class implements the Serializable interface
 *
 */
public class Test01 {
	public static void main(String[] args) throws IOException {
		//1) Create Person objects
		Person p1 = new  Person("lisi", 18);
		
		//2) Save p1 to a file
		ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("d:/obj.txt") );
		oos.writeObject(p1);
		oos.close();
	}
}
/**
 * Object deserialization
 * 	Using ObjectInputStream
 */
public class Test02 {

	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream ois  = new ObjectInputStream( new FileInputStream("d:/obj.txt"));
		Object obj = ois.readObject();
		//readObject() reads a Person object from a file and uses the Object type reference obj to save the reference to that object
		ois.close();
		
		System.out.println( obj );  //Calling toString() of Perosn object
		
		/*Scene description:
		 * 		When the Person class object is saved to a file
		 * 		A field was added to the Person class to modify the structure of the Person class.
		 * 		When deserialized again, the following exceptions occur
		 * java.io.InvalidClassException: com.bjpowernode.chapter06.objectinputstream.Person; 
		 * local class incompatible: stream classdesc serialVersionUID = -1846058886603673947,
		 *  local class serialVersionUID = -7054941406793751712
		 *  The exception is that the value of the serialVersionUID field in the stream is not equal to the value of the serialVersionUID field in the current bytecode file, resulting in an exception.
		 *  When deserializing, the value of the serialVersionUID field in the stream is not equal to the value of the field in the bytecode file 
		 *  
		 *Solutions:
		 *		When deserialization is guaranteed, the value of the serialVersionUID field in the stream is equal to that of the serialVersionUID field in the bytecode file.
		 *Way:
		 *		After the class implements the Serializable interface, a serialVersionUID field is usually added manually.  
		 */
	}

}

6 Print Stream

/**
 * PrintStream
 */
public class Test {

	public static void main(String[] args) throws IOException {
		//Establishing a byte stream by adding
		OutputStream out = new FileOutputStream("d:/log.txt" ,true ); 
		//Create a print stream
		PrintStream ps = new PrintStream(out);
		ps.print("hehe");
		ps.println("world");
		
		//The out member of the System class is the PrintStream stream. System.out represents the standard output device of the system, that is, the display.
		System.out.println("Print information on the display by default");
		//Modify the output direction of System.out
		System.setOut( ps );
		System.out.println("This line of data,Not shown on the screen., Output to ps In Print Stream,Namely log.txt file");
		
		//Sometimes, exception information is printed to a log file
		try {
			FileInputStream fis = new FileInputStream("g:/hehe.txt");
		} catch (Exception e) {
//			e.printStackTrace(); // / Print on screen
			e.printStackTrace(ps); 	//Print in ps stream
		}
	}
}

7 File class

Posted by jacksonmj on Sun, 28 Jul 2019 01:40:10 -0700