Java IO One

Source: Internet
Author: User

Introduction of 1.IO

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/89/37/wKiom1gMemrAP9qXAABRDMKpuzY025.png "title=" Qq20161023165225.png "alt=" Wkiom1gmemrap9qxaabrdmkpuzy025.png "/>

Classification of 2.IO Streams

Flow:

Input stream Read Data

Output stream writes out data

Data type:

BYTE stream

Byte input stream read data InputStream

Byte output stream writes out data outputstream

Character Stream

Character input stream read data reader

Character output stream write data Writer


We generally discuss IO flow, if not explicitly stated by that classification, by default, by data type.


3. Writing data

package com;import java.io.file;import  java.io.fileoutputstream;import java.io.outputstream;/** *  byte output stream operation step:  * 1. Creating a byte output stream object  * 2. Write data  * 3. Releasing Resources  */public class fileoutputstreamdemo {@ Suppresswarnings ("Resource") Public static void main (String[] args)  throws  Exception {file file = new file ("Hello.txt"); outputstream os = new  fileoutputstream (file,true);/** *  create a byte stream output object do the following things  *  invoke system functions to create files  *  create OS objects  *  point the OS object to this file  */os.write ("Hello, World". GetBytes ()); Os.close ();//Release Resources/** *  Why must close ()?  * 1. Make the Stream object garbage so that it can be reclaimed by the garbage collector  * 2. Notifies the system to release resources associated with the file  */}} 
Package Com;import java.io.fileoutputstream;import java.io.ioexception;import java.io.outputstream;/** * Bytes Output stream operation steps: * 1. Create byte output stream object * 2. Call the Write () method * 3. Free resources * public void write (int b) write a byte * public void Write (byte[] b) write a byte array * Public V  OID write (byte[] b,int offset,int Len) write part of a byte array * */public class FileOutputStreamDemo2 {public static void main (string[] args) throws IOException {outputstream os = new FileOutputStream ("Fos.txt"); os.write; Os.write ("HelloWorld"). GetBytes ()); Os.write (new byte[]{97,98, 99,100},1,3); Os.close ();}}


4. Append write for data

Package Cn;import Java.io.fileoutputstream;import java.io.outputstream;/** * How do I make a line break? * Write line break symbols. * Different systems are not the same for different line-break symbol recognition. * windows:\r\n * linux:\n * mac:\r * Some common advanced Notepad software is the ability to recognize any line break symbol. * * How to implement the data append write? * Public FileOutputStream (String name,boolean Append) * */public class Fileoutputstreamdemo {public static void main (STR Ing[] args) throws exception{//create byte output stream object OutputStream os = new FileOutputStream ("Fos.txt", true);//write data for (int i = 0; I < ; 10; i++) {os.write ("Hello" +i). GetBytes ()); Os.write ("\ n". GetBytes ());} Release resource Os.close ();}}


5. Adding byte output stream operations for exception handling

package cn;import java.io.filenotfoundexception;import java.io.fileoutputstream;import  java.io.ioexception;import java.io.outputstream;/** *  add byte output stream operation for exception handling  */public class  fileoutputstreamdemo1 {public static void main (String[] args)  { outputstream os = null;try {/** *  why the OS is assigned a value of null? *  because try{to os =  new fileoutputstream ("Fos.txt") in the event of an exception, *  then the OS has no default value, but the OS is a local variable ah, how can there be no default value?  */os = new fileoutputstream ("Fos.txt"); Os.write ("Java". GetBytes ());}  catch  (filenotfoundexception e)  {e.printstacktrace ();}  catch  (ioexception e)  {e.printstacktrace ();} finally{//if the OS is not NULL, why should close//add this judgment, if Os = new fileoutputstream ("Z://fos.txt"), the file does not exist, Then the exception is thrown//Of course Cath () will be captured, but the general program runs to finally, if there is no if judgment, is os.close (), and the OS is now null Ah,//null.close () Of course the newspaper nullpointerexception the IF (os != null) {//To protect CLose () will be executed, put into the finally inside the Try {os.close ();}  catch  (ioexception e)  {e.printstacktrace ();}}}}


6. Reading data

Package Cn;import java.io.fileinputstream;import java.io.inputstream;/** * Byte input stream operation steps: * 1. Create byte input Stream object * 2. Call the Read () method for reading data and display the data in the console * 3. Freeing resources * Read () method * public int read () throws Ioexcepiton: reads a byte data from the input stream and returns 1 */public if the end of the file is reached Inputstreamdemo {public static void main (string[] args) throws Exception {//create byte input stream object InputStream is = new FileInputStream ( "Fos.txt");//Call the Read () method to read the data and display the data in console int a = Is.read (); while ( -1! = a) {System.out.print ((char) a); a = Is.read ();} Release resource Is.close ();}}

Improved version

Package Cn;import java.io.fileinputstream;import java.io.inputstream;/** * Byte input stream operation steps: * 1. Create byte input Stream object * 2. Call the Read () method for reading data and display the data in the console * 3. Freeing resources * Read () method * public int read () throws Ioexcepiton: reads a byte data from the input stream and returns 1 */public if the end of the file is reached Inputstreamdemo {public static void main (string[] args) throws Exception {//create byte input stream object InputStream is = new FileInputStream ( "Fos.txt");//Call the Read () method to read the data and display the data in console int a = 0;while ((a = Is.read ())! =-1) {System.out.print ((char) a);} Release resource Is.close ();}}


7. Copying files

Package Cn;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.ioexception;import  Java.io.inputstream;import java.io.outputstream;/** * Copy text file * * Data source: Where to a.txt read data--fileinputstream * destination: Where to go B.txt Writing data--fileoutputstream */public class Filecopydemo {public static void main (string[] args) throws ioexception{//data source InputStream is = new FileInputStream ("A.txt");//destination OutputStream OS = new FileOutputStream ("B.txt"); int temp = 0;while ((te MP = Is.read ())! =-1) {os.write (temp);} Release resources Is.close (); Os.close ();}}

However, this approach is read one byte at a time, the efficiency is too slow, if you read large files, this way is not appropriate.

Package Cn;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.inputstream;import java.io.outputstream;/** * Copy files * read one character array at a time: public int read (byte[] b) * The return value is actually the number of bytes actually read if there is no more data because the end of the file has been reached, then 1 */pub Lic class FileCopy2 {public static void main (string[] args) throws exception{//create byte input stream object InputStream is = new Fileinputstre AM ("a.txt");//create a character stream output object OutputStream OS = new FileOutputStream ("B.txt");//define a byte array byte[] b = new Byte[1024];int temp = 0;w Hile ((temp = Is.read (b))! =-1) {os.write (b,0,temp);} Release resources Is.close (); Os.close ();}}

See a lot of people here collapsed, why do you write it? Haha, and listen to the ladyship to break down the code?

If the content in my a.txt file is

Hello

World

Java

Then we'll follow the code below.

Byte[] C = new byte[5];//first int len = Is.read (c); System.out.print (New String (c)); System.out.println (len); System.out.println ("--------------");//the Second len = Is.read (c); System.out.print (New String (c)); System.out.println (len); System.out.println ("--------------");//The third time Len = Is.read (c); System.out.print (New String (c)); System.out.println (len); System.out.println ("--------------");//fourth time Len = Is.read (c); System.out.print (New String (c)); System.out.println (len);

The result is this.

Hello5

--------------


Wor5

--------------

Ld

J5

--------------

Ava

J3

Why?

Actually, A.txt's content is the following.

hello\r\n

world\r\n

Java\r

We are not defining byte[] B = new Byte[5];

First time

Hello length is 5

Second time

\r\nwor length is also 5

In fact the second time is equivalent

B[0]=\r

b[1]=\n

B[2]=w

B[3]=o

B[4]=r

Of course, the bottom of these characters will be converted to byte, do not worry ah, I write just to let you understand

Third time

Ld\r\nj length is also 5

B[0]=l

B[1]=d

B[2]=\r

b[3]=\n

B[4]=j

Of course, the bottom of these characters will be converted to byte, do not worry ah, I write just to let you understand

four times

Ava\rj length is also 5 don't understand

Is this the third time?

B[0]=l

B[1]=d

B[2]=\r

b[3]=\n

B[4]=j

But this time it's only Ava, so is the array arranged in this way?

B[0]=a

B[1]=v

B[2]=a

So the 4th, 5th element, of course, is the third one, because this time there is no character to assign value.

b[3]=\n

B[4]=j

Do you understand me?

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/89/43/wKioL1gODtKzqFKZAABAKXxkOI0832.png "title=" Qq20161024210910.png "alt=" Wkiol1godtkzqfkzaabakxxkoi0832.png "/>

But how do we avoid this situation?

Look at the Len above, which is the length of each byte read. 5,5,5,3

So, if we change the code to look like this, is it possible to avoid the above problem?

Byte[] C = new byte[5];//first int len = Is.read (c); System.out.print (New String (C,0,len)); System.out.println (len); System.out.println ("--------------");//the Second len = Is.read (c); System.out.print (New String (C,0,len)); System.out.println (len); System.out.println ("--------------");//The third time Len = Is.read (c); System.out.print (New String (C,0,len)); System.out.println (len); System.out.println ("--------------");//fourth time Len = Is.read (c); System.out.print (New String (C,0,len)); System.out.println (len);

Hello5

--------------


Wor5

--------------

Ld

J5

--------------

Ava3

At this point, the output is what we want.

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/89/43/wKioL1gODwvRN_LMAAByixDHk2g938.png "title=" Qq20161024212017.png "alt=" Wkiol1godwvrn_lmaabyixdhk2g938.png "/>

So now can you read the code below?

Package Cn;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.inputstream;import java.io.outputstream;/** * Copy files * read one character array at a time: public int read (byte[] b) * The return value is actually the number of bytes actually read if there is no more data because the end of the file has been reached, then 1 */pub Lic class FileCopy2 {public static void main (string[] args) throws exception{//create byte input stream object InputStream is = new Fileinputstre AM ("a.txt");//create a character stream output object OutputStream OS = new FileOutputStream ("B.txt");//define a byte array byte[] b = new Byte[1024];int temp = 0;w Hile ((temp = Is.read (b))! =-1) {os.write (b,0,temp);} Release resources Is.close (); Os.close ();}}


8. Byte Buffer stream

Byte stream reading an array at a time is significantly faster than reading and writing one byte at a time. Oh, this is the buffer effect of adding arrays, Java itself in the design, also take into account the design idea (decorative mode), so provide a byte buffer stream


BYTE buffered output stream

Bufferedoutputstream

BYTE buffer input stream

Bufferedinputstream

Package Cn;import Java.io.bufferedoutputstream;import Java.io.fileoutputstream;import java.io.IOException;import Java.io.outputstream;public class Bufferedoutputstreamdemo {public static void main (string[] args) throws IOException { OutputStream OS = new Bufferedoutputstream (New FileOutputStream ("Bos.txt")); Os.write ("HelloWorld". GetBytes ()); O S.close ();}}
Package Cn;import Java.io.bufferedinputstream;import Java.io.fileinputstream;import java.io.ioexception;import Java.io.inputstream;public class Bufferedinputstreamdemo {public static void main (string[] args) throws IOException { InputStream is = new Bufferedinputstream (New FileInputStream ("Bos.txt")); byte[] B = new Byte[1024];int temp = 0;while (tem P=is.read (b))! =-1) {System.out.println (new String (B,0,temp));} Is.close ();}}



This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1865204

Java IO One

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.