Dear friends of Lebyte, Xiaole has come to share Java technology articles again. I wrote about the IO stream in the last article. This article focuses on the input stream and the output stream next time.
I. Input stream
Byte streams and character streams operate in almost the same way, except that the data units of operations are different. Byte stream can
To manipulate all files, the character stream operates only on plain text.
1. Abstract classes: InputStream and Reader
InputStream and Reader are the base classes of all input streams. They are two abstract classes and templates for all input streams. The methods defined in them can be used in all input streams.
There are three methods in InputStream:
There are three methods in Reader:
Comparing the methods provided by InputStream and Reader, we can see that the functions of these two base classes are basically similar. When the result is - 1, the end point of the input stream is indicated. InputStream and Reade are abstract and cannot create their instances directly. They can use their subclasses.
2. File Node Classes: FileInputStream and FileReader
FileInputStream and FileReader, both node flows, are directly associated with the specified file. Operational mode
It is basically the same.
1) Single byte read
Take FileInputStream as an example:
public class SingleFileRead { public static void main(String[] args) { // 1. Establishing Contact File Objects File file = new File("f:/IO/test.txt"); // 2. Selective flow InputStream in = null;// Enhance scope try { in = new FileInputStream(file); // 3. Operating single byte read long fileLength = file.length(); // Receiving the actual number of bytes read // Counter System.out.println(fileLength); long num = 0; // Loop reading while (num < fileLength) { char ch = (char) in.read(); System.out.println(ch); num++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("file does not exist,Cannot proceed to the next step"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("fail to read file"); } finally { try { // 4. Release of information if (in != null) { in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Failure to close file input"); } } } }
2) Batch reading (byte | character focus)
public class ReadFile { public static void main(String[] args) { //1. Byte Reading: Establishing Contact File Objects File file=new File("f:/IO/test.txt"); //2. Selective flow InputStream in=null;//Enhance scope try { in=new FileInputStream(file); //3. Operation Reads Buffer Array Continuously byte[]car=new byte[1024]; int len=0; //Receive actual read size //Loop reading while(-1!=(len=in.read(car))){ //Output, byte array converted to string String info=new String(car,0,len); System.out.println(info); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("file does not exist"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("fail to read file"); }finally{ try { //4. Release of information if(in!=null){ in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Failure to close file input"); } } } } //Character Read 1, Create Source File src=new File("f:/char.txt"); //2. Selective flow Reader reader=new FileReader(src); //3. Read operation char[] flush=new char[1024]; int len=0; while(-1!=(len=reader.read(flush))){ //Converting character arrays to strings String str=new String(flush,0,len); System.out.println(str); } //4. Releasing Resources reader.close(); //Lebyte Originality
3. Buffered InputStream and Buffered Reader
Buffering improves performance: byte streams can be nested directly; character buffer streams + new methods (polymorphism cannot be used)
//1. Creating Sources and Connecting File src =new File("test.txt"); //2. Selecting Buffer Stream InputStream is =new BufferedInputStream(new FileInputStream(src)); //3. Operation: multiple reads byte[] car =new byte[2]; int len =0; while(-1!=(len=is.read(car))){ //Get the contents of the array byte array to new String (byte array, 0,length) System.out.println(new String(car,0,len)); } //4. Releasing Resources is.close(); //Create a source: File src =new File("test.txt"); //Use Character Buffer Stream to Improve Performance Reading Files + New Method (Can't Use Polymorphism) BufferedReader br =new BufferedReader(new FileReader(src)); //Operation line reading String line=null; while(null!=(line=br.readLine())){ System.out.println(line); } //Releasing resources br.close();
4. Transform processing flow: Input Stream Reader
Conversion stream: Converting byte stream to character stream to deal with scrambling (encoding set, decoding set).
//read file File src =new File("test.txt"); //Conversion flow BufferedReader br =new BufferedReader( new InputStreamReader( new BufferedInputStream( new FileInputStream( src ) ),"utf-8" ) ); //Row reading String msg =null; while(null!=(msg =br.readLine())){ System.out.println(msg); } br.close();
5. ByteArray InputStream
The operating nodes are byte arrays, which are in jvm memory and managed by garbage collection mechanism, and do not need to be closed manually.
//1. Creating Sources byte[] src ="io Introduction to Learning".getBytes(); //2. Selective flow InputStream is = new ByteArrayInputStream(src); //3. Operations are consistent with documents byte[] flush =new byte[10]; int len =0; while(-1!=(len =is.read(flush))){ System.out.println(new String(flush,0,len)); } //4. Release is.close();
6. Data Processing Stream
It can handle the basic type + String and retain the type of data. The premise is that the reading order is the same as the writing order, otherwise the reading data is incorrect.
/** * Data + Type Output to File * @param destPath * @throws IOException */ public static void write(String destPath) throws IOException{ int point=2; long num=100L; String str="data type"; //Create Source File dest=new File(destPath); //Selective flow DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest))); //The order in which the operations are written prepares for reading dos.writeInt(point); dos.writeLong(num); dos.writeUTF(str); dos.flush(); //Releasing resources dos.close(); }
7. Object Processing Stream (Deserialization): ObjectInputStream
/** * Deserialization: * 1,Write before read * 2,Read objects need to know the specific type, read in turn * Be careful: * 1)Not all objects can serialize Serializable * 2)Not all attributes need to be serialized transient */ public static void read(String srcPath) throws FileNotFoundException, IOException, ClassNotFoundException{ //Create Source File src=new File(srcPath); //Selection stream Ojbect Input Stream ObjectInputStream dis=new ObjectInputStream( new BufferedInputStream( new FileInputStream(src) ) ); //The order in which the operation reads and writes must exist in order to read Object obj=dis.readObject(); if(obj instanceof Employee){ Employee emp=(Employee)obj; System.out.println(emp.getName()); System.out.println(emp.getSalary()); } obj=dis.readObject(); int[]arr=(int[])obj; System.out.println(Arrays.toString(arr)); //Releasing resources dis.close(); }
The IO stream in Java - the input stream is introduced here, and the output stream is discussed next time.
Lebyte originality, more Java technology dry goods continue to update, welcome attention.