Input stream output stream and file

Posted by sergeidave on Tue, 04 Feb 2020 14:54:33 +0100

Overview of IO
- what is IO (input, output)
- what is a set of orderly data sets with start and end points, such as file flow, network flow, etc
- difference from file: file is a static data presentation, and flow is a dynamic concept

The operation of data in Java is carried out in the way of flow. The objects of operation flow in Java are all under the java.io package

Stream is divided into character stream and byte stream according to the data type of operation
 The flow is divided into input flow and output flow according to the direction

In the java.io package, there are four abstract base classes

Character stream
	Reader  , Writer 
Byte stream
  InputStream , OutputStream 
  
All other IO operation classes are derived from them

All character streams end with a Reader or Writer, for example: FileReader, BufferedReader, FileWriter 
All byte streams end with InputStream or OutputStream, such as FileInputStream and fileoutputstream 
Standard IO exception handling
	//For example, write the contents of a collection to a file
		static void test2()  {
				List < string > namelist = new ArrayList < string > (); / / / write the list of people in the collection to a text file
				nameList.add("Chen cong");
				nameList.add("money into talent");
				nameList.add("Sun Baoxian");
				nameList.add("Chen Qiangqiang");
				nameList.add("Zhao Qing");
				
				Writer w=null;
				try {
				  w=new FileWriter("c: / / list. txt");
					
					for(String name: nameList) {
						w.write(name +"\r\n");
					}
					
					w.flush();
					w.close(); / / close the stream and clean up the resources			
					
				} catch (IOException e) {
					e.printStackTrace();
				} 
				finally {
					try {
						if(w!=null) {
							w.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			2 character stream Writer
 Writer  
	  BufferedWriter 
	  CharArrayWriter
	  OutputStreamWriter --> FileWriter
	  FilterWriter / / filter stream
	  PipedWriter / / pipeline flow
	  StringWriter 
	  
	  //Example write something in the file
		static void test() throws IOException {
			Writer w = new filewriter ("C: / 1. TXT", true); / / true means to write in append mode without overwriting the original content
			w.write("this year is 2020");
			w.write("\r\n"); / / write carriage return
			w.write("stay at home this year");
			
			//Character stream, when written out, writes to the buffer
			w.flush(); / / used to flush buffer
			w.close(); / / close the stream. It will automatically brush the buffer
			
			System.out.println("run successfully... ok");		
		}

====3 standard IO exception handling
//For example, write the contents of a collection to a file
static void test2() {
List nameList=new ArrayList();
nameList.add("Chen cong");
nameList.add("money into talent");
nameList.add("Sun Baoxian");
nameList.add("Chen Qiangqiang");
nameList.add("Zhao Qing");

				Writer w=null;
				try {
				  w=new FileWriter("c://List. txt ");
					
					for(String name: nameList) {
						w.write(name +"\r\n");
					}
					
					w.flush();
					w.close();  //Shut down, clean up resources			
					
				} catch (IOException e) {
					e.printStackTrace();
				} 
				finally {
					try {
						if(w!=null) {
							w.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			//Key points:
			1) stay finally Closed flow
			2) Before closing the flow,It's important to judge if it's not null

====4-character stream Reader
int read() / / read a single character. The returned int type is the ASII value of the read character. If the stream reads to the end, return - 1
int read(char [] buff) / / read the data into buff. The return value of type int indicates that several characters have been read. If the end is read, return - 1
int read(char [] buff, int off,int len) / / read the data to buff, start from the off position of the array, len indicates how many to read, and the return value of int indicates the number actually read

//The example reads data from a file and prints out the read characters. This example is a character by character reading
		static void test3() throws IOException {
			Reader r=new FileReader("c:/Name list.txt");
			int ch=0;
			while( (ch=r.read())!=-1  ) {
				System.out.print((char)ch);
			}	
			r.close();
		}
			
  //Example 2 receiving read data with character array
 	static void test4()throws IOException {
		Reader r=new FileReader("c:/Name list.txt");
		char [] buff=new char[1024];
		int len=r.read(buff);   //len represents how much data has been read
		
		String str=new String(buff,0,len);  //When you construct a string, you should construct it according to the data you actually read
		System.out.println("|"+str+"|");	
		r.close();
	}
	
	//Example 3 file copying this example is a character copying
	
			//Input: read from outside to memory
			//Output: write out the data in memory
			static void test5()throws IOException {
				//Read in
				Reader r =new FileReader("C:\\Users\\Administrator\\Desktop\\java99\\task\\texts.sql");
			
				//Write out
				Writer w =new FileWriter("C:\\test_copy.sql");
				
				int ch=0;
				while((ch=r.read())!=-1) {
					w.write(ch);	
				}
				
				r.close();
				w.close();	
			}
				
	//Example 4 copying of files
		 static void test6() throws IOException{
				Reader r = new FileReader("C:\\\\Users\\\\Administrator\\\\Desktop\\\\java99\\\\task\\\\texts.sql");
				Writer w =new FileWriter("C:\\test_copy_new.sql");
				
				char [] buff=new char[1024];
				
				int len=0;  //How many characters are actually read each time you read into an array
				
				while((len=r.read(buff))!=-1) {
					w.write(buff,0,len);
				}
				
				r.close();
				w.close();	
			}

====5 buffer flow and packaging
Buffer flow, there is buffer at the bottom (different from the buffer provided by the system, the buffer provided by the system directly deals with the target device, but the buffer of the buffer flow is through the wrapped object)

	There are many buffer streams, There are mainly  BufferedReader  BufferedWriter
	//"Package" convection
	//Convective enhancement
	
		static void test7() throws IOException {
			Writer w=new FileWriter("c:/a.txt");
			BufferedWriter bw=new BufferedWriter(w);
			
			bw.write("This is the first line");
			bw.newLine(); //Write newline, which is the way to increase buffer flow
			bw.write("This is the second line");
			
			bw.flush();
			bw.close();	
		}
		
		
		//The readLine() method of BufferedReader can read one line at a time
	  static void test8() throws IOException{
				Reader r =new FileReader("c:/test_copy.sql");		
				BufferedReader br =new BufferedReader(r);
				
				String str=null;
				while( ( str=br.readLine() )!=null  ) {
					System.out.println(str);
				}
				
				br.close();   //Inside it is r.close();		
			}
				
					
	//Decoration mode	
		public class Test2 {
			public static void main(String[] args) {
				Japan p =new Japan();
				
				NiceJapan nicejapan=new NiceJapan(p);
				nicejapan.speak();
				nicejapan.eat();
			}
		}
		
		class Japan{
			void speak() {
				System.out.println("Yo West..");
			}
		}
		
		class NiceJapan{
			private Japan japan;
			
			NiceJapan(Japan japan){
				this.japan=japan;
			}
			
			void speak() {
				System.out.println("nod the head..");
				System.out.println("Bend the waist..");
				japan.speak();	
				System.out.println("Kowtow..");
			}
			
			void eat() {
				System.out.println("Being eat....");
			}
		}	
			
			
  //Interface decoration mode is used
	public class Test2 {
		public static void main(String[] args) {
			/*
			   Japan p=new Japan(); 
			   p.speak(); 
			   p.eat(); 
			   p.work();
			 */
			
			Person p=new Japan(); 	
			p= new NiceJapan(p);
			
			p.eat();
			p.speak();
			p.work();		
		}
	}
	
	interface Person{
		void speak();
		void eat();
		void work();
	}
	
	class Japan implements Person{
		public void speak() {
			System.out.println("A pale speech");
		}
	
		public void eat() {
			System.out.println("Pale eating");
		}
	
		public void work() {
			System.out.println("A pale job");
		}
	}
	
	
	//In general, the decorated class and the decorated class should implement the same interface
	class NiceJapan implements  Person{
		Person p;
		NiceJapan(Person p){
			this.p=p;
		}
		
		public void speak() {
			System.out.println("Warawa La...");
			p.speak();
			System.out.println("Oh, oh....");
		}
		public void eat() {
			System.out.println("Pray first..");
			p.eat();
		}
		public void work() {
			System.out.println("Bow first..");
			p.work();
			System.out.println("Stand up again..");
		}	
	}

====6-byte stream
The suffix of byte stream is InputStream or OutputStream

	//The example uses byte stream to read and write files
		static void test1() throws IOException {
			OutputStream out =new FileOutputStream("c:/2.txt");
			out.write("root This is a string admin".getBytes());   //The byte stream does not use flush, and the byte does not directly write the string, so it needs to be converted into a byte array
			out.close();
			
			InputStream in =new FileInputStream("c:/2.txt");
			
		  //in.read() reads a byte from the stream, and the returned value is the code value corresponding to this byte
			
			int ch=0;
			while((ch=in.read())!=-1) {
				System.out.print((char)ch);  //It can be found that there is a disorder in Chinese
			}
			
			in.close();
		}
			
	//The biggest difference between character stream and byte stream:
	//Character stream is always read by character (as for a character to read several bytes, we don't need to consider), which is suitable for processing text file
	//Byte stream is always read by byte (even if this byte can't form a character), which is suitable for processing binary files such as pictures, sounds, etc
	
	
	//Example, read with byte array
		static void test2() throws IOException  {
			InputStream in =new FileInputStream("c:/test_copy.sql");
			byte [] buff=new byte[20];
			
			int len=0;
			while((len=in.read(buff))!=-1) {
				String str=new String(buff,0,len);
				System.out.println(str);
			}
			
			in.close();	
		}
		
		//Note that sometimes there will be garbled code in Chinese
		
	//Example about the available() method
		//Its function is to determine how many bytes remain unread in the stream
			static void test3()throws IOException {
					InputStream in =new FileInputStream("c:/test_copy.sql");
					
					System.out.println(in.available()); //23390
					
					in.read();
					in.read();
					in.read();
					in.read();
					
					System.out.println(in.available());	//23386
			}
			
	 //The example uses available() to get the length of the data, and then processes it
			static void test2() throws IOException  {	
				InputStream in =new FileInputStream("c:/test_copy.sql");
				byte [] buff=new byte[in.available()];
				in.read(buff);
				String str=new String(buff);
				System.out.println(str);
				
				in.close();
			}
			
	 //Copy of example pictures
	 static void test4() throws IOException {
			InputStream in=new FileInputStream("C:\\Users\\Administrator\\Desktop\\1.jpg");
			OutputStream out =new FileOutputStream("C:\\Users\\Administrator\\Desktop\\1_copy.jpg");
			
			byte [] buff=new byte [in.available()];
			in.read(buff);
			out.write(buff);
			
			in.close();
			out.close();		
		}
		
		//Note that the above is suitable for small files

====7 conversion flow
InputStreamReader, OutputStreamWriter

 Flow byte input to character input
						 InputStreamReader     public class  InputStreamReader extends Reader  
	 //Flow byte output to character output
						 OutputStreamWriter    public class  OutputStreamWriter extends Writer  
									
			  1) InputStreamReader 
	        //It has four constructors:
				  InputStreamReader(InputStream in) 
				  InputStreamReader(InputStream in, Charset cs) 
					InputStreamReader(InputStream in, CharsetDecoder dec)  //CharsetDecoder decoder
					InputStreamReader(InputStream in, String charsetName) 

	      2) OutputStreamWriter  
					//It has four constructors:
					OutputStreamWriter(OutputStream out) //Create an OutputStreamWriter that uses the default character encoding. 
					OutputStreamWriter(OutputStream out, CharsetEncoder enc) // Creates an OutputStreamWriter that uses the given character set. 
					OutputStreamWriter(OutputStream out, String charsetName) // Creates an OutputStreamWriter that uses the given character set encoder. 
	        OutputStreamWriter(OutputStream out, String charsetName) // Creates an OutputStreamWriter that uses the specified character set.
	        
	 //Using InputStreamReader to convert a byte into a character stream
			static void test1() throws IOException {
				//Byte stream
				InputStream in=new FileInputStream("c:/Name list.txt");
				
				//Wrap byte stream with transform stream
				InputStreamReader inr=new InputStreamReader(in);
				
				//Use buffer stream to package conversion stream
				BufferedReader br =new BufferedReader(inr);
				
				String str=null;
				
				while((str=br.readLine())!=null) {
					System.out.println(str);
				}
				
				br.close();	
			}

 //For example, change a line of letters entered from the keyboard to uppercase
		static void test2() throws IOException {		
			BufferedReader br=	new BufferedReader( new InputStreamReader(System.in)); //Stream stack		
			String str=null;		
			while((str=br.readLine())!=null) {
				System.out.println(str.toUpperCase());
			}
			
			br.close();
		}

====8 practice
From an input stream, read characters, change them to uppercase, and store them in the output stream
public static void main(String[] args) throws IOException {
InputStream in=new FileInputStream("c:/a.txt");
OutputStream out =new FileOutputStream("c:/a_copy.txt");

			transform(in,out);
			
			in.close();
			out.close();
			System.out.println("ok");
		}
		
		 public static void main(String[] args) throws IOException {
				transform(System.in,System.out);
				System.out.println("ok");
		 }

			
		/**
		 * Parameter 1 input flow
		 * Valuepoint 2 output flow
		 * @throws IOException 
		 */
		static void transform(InputStream in,OutputStream out) throws IOException {
			int ch=0;
			
			while((ch=in.read())!=-1   ) {
				out.write(  Character.toUpperCase(ch)  );
			}	
		}
Published 12 original articles, won praise 0, visited 155
Private letter follow

Topics: SQL Java network encoding