Summary of IO operations in java (1)

Source: Internet
Author: User
Document directory
  • Ghost stream
  • Byte stream

IO, short for Input and Output. In java, IO involves a large range. Here we mainly discuss the reading and writing of file content.

Other knowledge points will be placed in subsequent chapters (I think the article is too long and no one has the patience to go to the end)

 

There are two main types of operations on file content:

They are:

  Ghost stream

  Byte stream

The streams have two abstract classes:WriterReader

Its subclassFileWriterAndFileReaderAllows you to read and write files.

BufferedWriterAndBufferedReaderProvides the buffer function to improve efficiency.

 

Likewise, a byte stream has two abstract classes:InputStreamOutputStream

Its corresponding subclass hasFileInputStreamAndFileOutputStreamImplement file read/write

BufferedInputStreamAndBufferedOutputStreamProvides the buffer function.

 

I made a lot of mistakes when I was learning IO, and some code on the Internet could not be compiled, or even the style was very different. Therefore, for beginners, please note:

1. The code in this article is long and should not be omitted, mainly because it is necessary to develop good coding habits as a newbie.

2. This Article is compiled in linux, which is similar to File. pathSeparator and File. separator. This representation is for cross-platform and robust considerations.

3. Some operations in the Code have multiple execution methods. I have adopted the method 1... method 2... expression, which can be compiled with just a few simple annotations.

4. the Code does not throw exceptions on the main method, but captures them separately, causing code to be too long. If you only test the code or do not want to have good programming habits, you can just throw it ......

5. There will be no repeated comments in similar functional areas. If the newbie cannot understand the following code, it must be that the above does not understand clearly.

 

Ghost stream Instance 1: Writing streams
Import java. io. file; import java. io. fileWriter; import java. io. IOException; public class Demo {public static void main (String [] args) {// create the path and name of the File to be operated // Where, File. separator indicates the system-related separator. in Linux, it is: \ String path = File. in Windows. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; // As IO operations throw an exception, the reference FileWriter w = null is defined externally in the try statement block; try {// create a new FileWriter object // If You Need to append data instead of Overwriting data, use the FileWriter (path, true) constructor w = new FileWriter (path); // write the string to the stream, \ r \ n indicates that w has a better line feed. write ("Nerxious is a good boy \ r \ n"); // to view the write effect immediately, call w. flush () method w. flush ();} catch (IOException e) {e. printStackTrace ();} finally {// if an exception occurs before, the w object cannot be generated // Therefore, a judgment should be made to avoid NULL pointer exception if (w! = Null) {try {// close the stream resource. Capture the exception again w. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

After compilation, generate a file under the Directory and write the string

 

Instance 2: Reading the upstream stream
Import java. io. file; import java. io. fileReader; import java. io. IOException; public class Demo2 {public static void main (String [] args) {String path = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; FileReader r = null; try {r = new FileReader (path); // Method 1: read a single character // read each time, move one character down in int temp1 = r. read (); System. out. println (char) temp1); int temp2 = R. read (); System. out. println (char) temp2); // Method 2: read through the loop // read () method returns-1/* while (true) {int temp = r. read (); if (temp =-1) {break;} System. out. print (char) temp);} * // method 3: Simplified cyclic read Operations // read a single character, when temp is not equal to-1, print the character/* int temp = 0; while (temp = r. read ())! =-1) {System. out. print (char) temp);} * // Method 4: read to the character array/* char [] buf = new char [1024]; int temp = r. read (buf); // convert the array to a string for printing. The following parameter indicates // if the character array is not full, after being converted to a string, other characters may appear at the end of the string. // Therefore, the number of characters read will be converted to the string System. out. println (new String (buf, 0, temp); * // Method 5: Read to character array optimization // sometimes the file is too large, the size of the array to be defined cannot be determined. // Therefore, the length of the array is generally 1024. Read/* char [] buf = new char [1024] cyclically; int temp = 0; while (temp = r. read (buf ))! =-1) {System. out. print (new String (buf, 0, temp);} */} catch (IOException e) {e. printStackTrace ();} finally {if (r! = Null) {try {r. close ();} catch (IOException e) {e. printStackTrace ();}}}}}

Effect after compilation:

 

Example 3: copy a text file
Import java. io. file; import java. io. fileReader; import java. io. fileWriter; import java. io. IOException; public class Demo {public static void main (String [] args) {String doc = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; String copy = File. separator + "home" + File. separator + "siu" + File. separator + "life" + File. separator + "lrc.txt"; FileRe Ader r = null; FileWriter w = null; try {r = new FileReader (doc); w = new FileWriter (copy); // Method 1: write int temp = 0 for a single character; while (temp = r. read ())! =-1) {w. write (temp);} // Method 2: Writing in character array mode/* char [] buf = new char [1024]; int temp = 0; while (temp = r. read (buf ))! =-1) {w. write (new String (buf, 0, temp);} */} catch (IOException e) {e. printStackTrace ();} finally {// determine whether a null pointer is referenced, and then close the stream if (r! = Null) {try {r. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (w! = Null) {try {w. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

After compilation, copy the lrc.txt file under the lifeobject.

 

Example 4: Copy text files using the swap Stream Buffer
Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. file; import java. io. fileReader; import java. io. fileWriter; import java. io. IOException; public class Demo {public static void main (String [] args) {String doc = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; String copy = File. separator + "home" + File. separator + "siu" + File. separator + "life" + File. separator + "lrc.txt"; FileReader r = null; FileWriter w = null; // create a buffer reference BufferedReader br = null; BufferedWriter bw = null; try {r = new FileReader (doc); w = new FileWriter (copy ); // create a buffer object // put the FileReader and FileWriter objects that require higher efficiency into the constructor. // Of Course, you can also use the anonymous object method br = new BufferedReader (new FileReader (doc); br = new BufferedReader (r); bw = new BufferedWriter (w); String line = null; // read rows, Until null // readLine () is returned, only the data before the line break is returned while (line = br. readLine ())! = Null) {// use the BufferWriter object's write method bw. write (line); // wrap the line after writing the file content // newLine () the method depends on the platform. // in windows, the line feed is \ r \ n. // in Linux, the line feed is \ nbw. newLine () ;}} catch (IOException e) {e. printStackTrace ();} finally {// here, you no longer need to capture exceptions for FileReader and FileWriter objects. // disable the buffer. Disable the stream object in the buffer if (br! = Null) {try {r. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (bw! = Null) {try {bw. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

 

Byte stream instance 5: Writing of byte streams
Import java. io. file; import java. io. fileOutputStream; import java. io. IOException; public class Demo {public static void main (String [] args) {String path = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; FileOutputStream o = null; try {o = new FileOutputStream (path); String str = "Nerxious is a good boy \ r \ n "; byte [] buf = str. getBytes (); // You can also directly Use o. write ("String ". getBytes (); // because the string is an object, you can directly call method o. write (buf);} catch (IOException e) {e. printStackTrace ();} finally {if (o! = Null) {try {o. close ();} catch (IOException e) {e. printStackTrace ();}}}}}

To facilitate terminal display, add \ r \ n to the above compiled files

In fact, only \ n is used for line feed in linux.

 

Example 6: Reading byte streams
Import java. io. file; import java. io. fileInputStream; import java. io. IOException; public class Demo {public static void main (String [] args) {String path = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "demo.txt"; FileInputStream I = null; try {I = new FileInputStream (path); // Method 1: read a single character // note that, here I use English text to test the effect is good // but the Chinese language is tragic, but the following two methods work well int ch = 0; while (ch = I. Read ())! =-1) {System. out. print (char) ch);} // Method 2: array loop read/* byte [] buf = new byte [1024]; int len = 0; while (len = I. read (buf ))! =-1) {System. out. println (new String (buf, 0, len);} * // method 3: the standard size array reads/* // determines the number of bytes returned by an array of just size // available () method. // However, if the file is too large, the memory overflows, it's a tragedy !!! The above method is good. byte [] buf = new byte [I. available ()]; I. read (buf); // because the array size is good, you do not need to set the starting point System in the constructor when converting to a string. out. println (new String (buf); */} catch (IOException e) {e. printStackTrace ();} finally {if (I! = Null) {try {I. close ();} catch (IOException e) {e. printStackTrace ();}}}}}

Read files to the terminal

 

Instance 7: copying binary files
Import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; public class Demo {public static void main (String [] args) {String bin = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "a person's life"; String copy = File. separator + "home" + File. separator + "siu" + File. separator + "life" + File. separator +" A person's life "; FileInputStream I = null; FileOutputStream o = null; try {I = new FileInputStream (bin); o = new FileOutputStream (copy); // read and write files cyclically, to complete the replication of byte [] buf = new byte [1024]; int temp = 0; while (temp = I. read (buf ))! =-1) {o. write (buf, 0, temp) ;}} catch (IOException e) {e. printStackTrace () ;} finally {if (I! = Null) {try {I. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (o! = Null) {try {o. close ();} catch (IOException e) {e. printStackTrace ();}}}}}

Replication effect,

Example 8: copying binary files using the byte stream buffer
Import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; public class Demo {public static void main (String [] args) {String bin = File. separator + "home" + File. separator + "siu" + File. separator + "work" + File. separator + "a person's life"; String copy = File. separator + "home" + File. separator + "siu" + File. separator + "life" + File. separator + "one person living"; FileInputStream I = null; FileOutputStream o = null; BufferedInputStream bi = null; BufferedOutputStream bo = null; try {I = new FileInputStream (bin ); o = new FileOutputStream (copy); bi = new BufferedInputStream (I); bo = new BufferedOutputStream (o); byte [] buf = new byte [1024]; int temp = 0; while (temp = bi. read (buf ))! =-1) {bo. write (buf, 0, temp) ;}} catch (IOException e) {e. printStackTrace () ;} finally {if (bi! = Null) {try {I. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (bo! = Null) {try {o. close ();} catch (IOException e) {e. printStackTrace ();}}}}}

The two directories have a life-saving file. By the way, this song is quite good.

 

When beginners learn to use the primary stream and word throttling, they will have no doubt: When should they use the primary stream and when should they use the byte stream?

As a matter of fact, you should know that the so-called ghost stream must be used for operations similar to text files or character files.

Byte streams operate on binary files that cannot directly obtain text information, such as video clips, mp3 files, and video files.

To put it bluntly, it is stored in bytes on the hard disk, but the compaction stream is more convenient on the operating text.

In addition, why should we use the buffer zone?

We know that downloading software such as Thunder has a cache function, and the hard disk itself has a buffer.

Think about it. If data is read and written, regardless of the size of the data, it will inevitably cause a great burden on the hard disk and it will feel uncomfortable.

The same is true for people. If you don't want to eat a meal at a time, feed a spoonful every minute. What do you think?

Therefore, using a buffer can effectively improve efficiency when reading and writing large files

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.