1.IO stream classification
According to the direction: input stream (such as the file you copied) output stream (such as the new file you copied)
By unit: byte stream (data transmission in bytes)
Character stream (data transmission in characters char)
According to function: node flow (equivalent to needle) filter flow (equivalent to needle tube)
2. Byte stream
2.1 In/OutputStream
InputStream is the unified parent class of input stream, which is an abstract class
Three methods
int read()
int read(byte[] data) is the most commonly used (the parameters in it will be explained later)
int read(byte[] data,int off,int len)
OutputStream is the unified parent class of the output stream and is an abstract class
There are also three corresponding methods
write(int data)
write(byte[] data)
write(byte[] data,int off,int len) is the most commonly used
=========================================================================
FileInputStream reads the file from the node stream (the needle for injection must be inserted into the file, not the directory (an exception will be reported))
The output file of FileOutputStream is also a node stream (the needle for injection must be inserted into the file, not the directory (an exception will be reported))
*: FileInputStream is most commonly used. The read(byte[] data) parameter represents the data size of a transmission. By default (write nothing) one byte (slow and touching)
FileInputStream takes - 1 as the end of reading
import java.io.*; public class TestFileInputStream{ public static void main(String[] args)throws Exception{ FileInputStream fis = new FileInputStream("abc.txt"); int data = 0; while((data = fis.read())!=-1//(end reading when equal to - 1){ System.out.print((char)data); } fis.close(); } } //abc.txt is helloworld //This method is not recommended, but more recommended /*public static void main(String[] args)throws Exception{ FileInputStream fis = new FileInputStream("abc.txt"); int len; byte[] data = new byte[3];//byte The size of the array represents the amount of data transported at a time while((len = fis.read(data))!=-1){ for(int i = 0;i<len;i++){ System.out.print((char)data[i]); } } fis.close();//Close the flow in time after use } */
*: FileOutputStream uses write(byte[],int,int) most often
Writes the (second int) bytes from the offset (first int) in the specified byte array byte to this file output stream
This method (of node output stream) is very dangerous. When the file you connect to does not exist, it will automatically create that file for you.
However, when you connect an existing file, it will create a new blank file to replace that file at the moment of creating the stream, so you need to pay attention to it before use.
If you need to continue adding other contents after the original file (for example, you want to add the contents of txt file b after a txt file a), you can specify the addition mode in the construction method
FileOutputStream fos = new FileOutputStream("a.txt",true)
=========================================================================
2.2 TWR syntax
Normally, all statements that create new streams need to add trycatch to handle exceptions. So it will
import java.io.*; public class TestFileCopyWithTryCatch{ public static void main(String[] args){ FileInputStream fis = null; FileOutputStream fos = null; try{ fis = new FileInputStream("1.mp3"); fos = new FileOutputStream("3.mp3"); byte[] data = new byte[5<<20];//5*1024*1024 int len; while((len = fis.read(data))!=-1){ fos.write(data,0,len); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ fis.close();//Make sure that FIS Close () must be implemented, so it is put in finally }catch(Exception e){ e.printStackTrace(); }finally{ try{ fos.close();//Not putting the above try is to prevent the closing failure of the above try from causing the closing failure of fos }catch(Exception e){ e.printStackTrace(); } } } } }
Long and touching..
Therefore, JDK7 0 introduced a new syntax TWR: try - with - Resources -- > trycatch with resource control
So the code becomes
import java.io.*; public class TestFileCopyWithTryCatch{ public static void main(String[] args){ FileInputStream fis = null; FileOutputStream fos = null; try(fis = new FileInputStream("1.mp3");//The statement that assigns a value to the stream is put into try(), and the method body is written in {} fos = new FileOutputStream("3.mp3");//final; (optional) { byte[] data = new byte[5<<20];//5*1024*1024 int len; while((len = fis.read(data))!=-1){ fos.write(data,0,len); } }catch(Exception e){ e.printStackTrace(); } } }
It will automatically help you close the flow. It doesn't need you to worry. It's great
2.3 BufferedIn/OutputStream
Bufferedinputstream is basically the same as the above (FileInputStream), but it is not a needle, but a pipe (filtered stream).
BufferedOutputStream is basically the same as the above (FileOutStream), but it is not a needle, but a pipe (filtered stream).
1. As filter streams, they are designed to add buffer space to the original node stream, so as to improve the throughput of each read and write, and then improve the efficiency (just like StringBuffer)
2. They cannot connect directly to files, but to other streams (node streams)
3. The second parameter of their construction method allows you to specify the size of the buffer space. By default, 8192 bytes is 8k
4. The most commonly used method for bufferedinputstream is read()
5. The most common method of Output , is write(int data), because the buffer size is set in the construction method
6.BufferedInputStream also takes - 1 as the end of reading
7.BufferedOutputStream is a buffered output stream
When using buffered output streams, be sure to empty the buffer in time
To prevent data from being lost due to stranded buffer space
Under what conditions will the buffer be emptied:
1. Automatic emptying when full, no operation required
2. Closing the stream triggers the emptying of the buffer
3. Actively empty buffer flush();
8. What is the reason why the file becomes smaller after copying and what is the reason why the file becomes larger after copying
Smaller: the output stream with buffer is used, but the buffer is not emptied in time
So the data stays in the buffer space, resulting in loss
Larger: redundant data is written out by using write(byte[] data) which only passes array
import java.io.*; public class TestBufferedStream{ public static void main(String[] args)throws Exception{ FileInputStream fis = new FileInputStream("1.mp3");//syringe needle BufferedInputStream bis = new BufferedInputStream(fis,5<<20);//Needle tube (needle) FileOutputStream fos = new FileOutputStream("3.mp3");//syringe needle BufferedOutputStream bos = new BufferedOutputStream(fos,5<<20); int data; while((data = bis.read())!=-1){ bos.write(data); } bis.close(); //bos.flush(); Manual flush refresh is not required because close() will refresh automatically bos.close(); } }
2.4 DataIn/OutputStream
DataInputStream - input stream bytes flow through the filter stream
DataOutputStream - output stream bytes flow through the filter stream
Function: as filter streams, they are used to add the function of reading and writing basic data types to the original node stream
They can't connect to other streams directly
DataInputStream core method readXxxx(); There is a return value
DataOutputStream core method writeXxxx(); To parameter
At the end of judgment:
DataInputStream cannot end reading with - 1
Instead, once the end of the file is reached, it continues to try to read
Eofexception = > end of file will be triggered directly
Therefore, trycatch can modify the error report manually
Or use a set, array, etc. to save objects. When read, just take them out of the set or array one by one
import java.io.*; public class TestDataStream{ public static void main(String[] args)throws Exception{ /* int level = 835; FileOutputStream fos = new FileOutputStream("save.data"); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(level);//Pay attention to the core method dos.close(); */ FileInputStream fis = new FileInputStream("save.data"); DataInputStream dis = new DataInputStream(fis); int data = dis.readInt();//Pay attention to the core method dis.close(); System.out.println(data); } }
2.5 ObjectIn/OutputStream
With basic data types, reference data types also have input and output stream methods.
ObjectInputStream - input stream bytes flow through the filter stream
ObjectOutputStream - output stream bytes flow through the filter stream
1. As filter streams, they are designed to add the function of reading and writing objects to the original node stream
2. As filter streams, they can't connect files directly. They can only connect other streams!
3. The core method provided by objectinputstream is called readObject()
4. The core method provided by objectoutputstream writeObject()
5.ObjectInputStream also cannot use - 1 as the end of reading ID
Because Integer Byte Short can read - 1
So it also reaches the end of the file and then continues to read
Just trigger EOFException directly
6. To persist, you first need to serialize the implementation serializable
The type of object you want to persist must implement the serialization interface
If there are properties of other reference types, even the type of the property must implement the serialization interface
If some attributes are irrelevant and do not need to participate in persistence, you can use the transient modifier
Transient = > transient = > non persistent
If you want to persist a collection object, you must ensure that the element types in the collection must implement the serialization interface
If you want to persist a TreeSet or TreeMap that uses a comparator
Even the classes of comparators need to implement the serialization interface, because comparators are one of their properties
import java.io.*; import java.util.*; public class TestObjectStream{ public static void main(String[] args)throws Exception{ /* Date today = new Date(); FileOutputStream fos = new FileOutputStream("Moonlight treasure box data"); ObjectOutputStream dos = new ObjectOutputStream(fos); dos.writeObject(today); dos.close(); */ FileInputStream fis = new FileInputStream("Moonlight treasure box.data"); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = ois.readObject(); ois.close(); Date theDate = (Date)obj; System.out.println(theDate); } }
import java.io.*; public class TestObjectStream2{ public static void main(String[] args)throws Exception{ /*Elephent el = new Elephent("Elephant "); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Refrigerator. data")); oos.writeObject(el); oos.close(); */ ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Refrigerator.data")); Object obj = ois.readObject(); ois.close(); Elephent ele = Elephent(obj); System.out.println(ele.name); //There is no pc attribute } } class Computer{ String logo; public Computer(String logo){ this.logo = logo; } } class Elephent implements Serializable{ String name; //Transient = transient = not involved in persistence~ transient Computer pc; public Elephent(String name){ this.name = name; pc = new Computer("Lenovo"); } }
3. Character stream
3.1Read/Writer
Reader , all character input streams are unified parent abstract classes
int read()
int read(char[] data)
int read(char[] data,int off,int len)
Writer is a unified parent abstract class of all character output streams
write(int data)
write(char[] data)
write(char[] data,int off,int len)
3.2FileReader/Writer
FileReader input stream character stream node stream
FileWriter output stream character stream node stream
They are all node flows, and the construction method allows the String path / File object to be passed in
They can only connect files, not folders, otherwise an exception will be thrown
FileReader most commonly used read(char[] data)
FileWriter # most commonly used write(char[],int,int)
Other functions of FileWriter are the same as FileOutputStream (danger, append mode)
FileReader also ends with - 1
After use, close the stream at the first time and release the file occupation status
You can also use TWR syntax to handle exceptions (JDK 7.0)
import java.io.*; public class TestFileReader{ public static void main(String[] args)throws Exception{ FileReader fis = new FileReader("abc.txt"); int data; while((data = fis.read())!=-1){ System.out.print((char)data); } fis.close(); } }
3.3 BufferedReader/Writer
BufferedReader # character stream input flows through filter stream
BufferedWriter - character stream output flows through filter stream
1. As filter streams, they are designed to add variable buffer space to the original node stream, so as to achieve one behavior unit
Reading and writing
2. They are all filtered streams, which can only be connected to other streams, and cannot be directly connected to files
3.BufferedReader core method String readLine()
4.BufferedReader does not take - 1 as the ID of the end of reading, but null
5.BufferedWriter core method write(String) + newLine()
import java.io.*; public class TestBufferedReader{ public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new FileReader("focus.txt")); String str; while((str = br.readLine())!=null){ if(str.contains("flow")){ System.out.println(str); } } br.close(); } }
import java.io.*; public class TestBufferedWriter{ public static void main(String[] args)throws Exception{ BufferedWriter bw = new BufferedWriter(new FileWriter("Goose goose goose.txt")); bw.write("Goose goose goose"); bw.newLine();//Line feed bw.write("Song Xiang Tiange"); bw.newLine();//Line feed bw.write("White hair floating green water"); bw.newLine();//Line feed bw.write("Goose's paw stirs clear waves"); //bw.flush();close auto flush bw.close(); } }
3.4 PrintWriter (better than BufferedWriter)
1. It can be used as both node flow and filter flow
Constructors allow you to pass in output streams or file objects or file paths
2. It can connect both byte stream and character stream
Constructor allows InputStream / writer to be passed in
3. When used as a node flow, the second parameter of its construction method
Character encoding can be specified
new PrintWriter("abc.txt","utf-8");
4. When used as a filter stream, the second parameter of its construction method
You can specify to automatically empty the buffer~
new PrintWriter(new FileWriter("abc.txt",true),true);
Two true s in this line of code represent appendMode / autoFlush respectively
5. println() = write() + newLine()
6. You are too familiar with its twin brother
System.out.println(); Out is PrintStream
To sum up, write text files in behavioral units
We don't choose BufferedWriter at all, but PrintWriter
import java.io.*; public class TestPrintWriter{ public static void main(String[] args)throws Exception{ PrintWriter pw = new PrintWriter("spring morning.txt"); pw.println("Spring sleep without dawn"); pw.println("Birds sing everywhere"); pw.println("The sound of wind and rain at night"); pw.print("How many flowers do you know"); pw.close(); } }
3.5 InputStreamReader/OutputStreamWriter
InputStreamReader
OutputStreamWriter
*: a bridge between byte flow and character stream. A tool for converting byte stream into character stream
import java.io.*; public class TestUTF8{ public static void main(String[] args)throws Exception{ /* PrintWriter pw = new PrintWriter("Testing txt","utf8"); pw.println("Looking at the sword with a lamp in the drunken room "); pw.println("Dream back to blowing horn and camp "); pw.close(); */ //FileReader fr = new FileReader("test. txt"); FileInputStream fis = new FileInputStream("test.txt"); //Bridge converter = > a bridge from byte flow to character stream. It is a tool for converting byte stream into character stream InputStreamReader r = new InputStreamReader(fis,"utf8");//You can specify the encoding format BufferedReader br = new BufferedReader(r); String str; while((str = br.readLine())!=null){ System.out.println(str); } br.close(); } }