Java I/O learning (with examples and explanations)

Source: Internet
Author: User
Tags finally block

I. Java I/O class structure and basic concepts of streams

Before reading an instance of Java I/O, we need to know some concepts before we look at the class diagram of Java I/O:

Java I/O is primarily read-write data in the form of streams.

A stream is a set of sequences of bytes that have a starting point and an end point, a generic or abstract of the data transfer. That is, the transmission of data between the two devices is called the flow, the essence of the flow is data transmission, according to the data transmission characteristics of the stream abstracted into various classes, convenient and more intuitive data manipulation.

Depending on the data type of the data being processed, it can be divided into: character stream and byte stream.

The main differences between character streams and byte streams are:

1. When the byte stream is read, a byte is returned, and the character stream is read to one or more bytes using the byte throttle (the number of bytes in Chinese corresponds to two, which is 3 bytes in the UTF-8 Code table). First check the specified encoding table and return the found characters.

2. The byte stream can handle all types of data, such as: Pictures, Mp3,avi video files, and character streams can only handle characters data. As long as you are dealing with plain text data, you should prioritize the use of character streams, in addition to byte streams.

3. In fact, the byte stream in the operation itself does not use the buffer (memory), the file itself is directly manipulated, and the character stream is used in the operation of the buffer, through the buffer to manipulate the file.

Here we take a file operation as an example to learn more.

Second, character stream instance

As mentioned before, "as long as the processing of plain text data, priority should be given to the use of character streams, in addition to the word stream." So this character stream operation instance is the operation TXT file. Read and write to the operation.

2.1. Some concepts

Previously, we needed to understand some concepts.

Java uses 16-bit Unicode to represent strings and characters. We can specify the encoding of the string to write when writing a stream of characters.

Here bloggers stick out the character stream class diagram structure, convenient for ape friends to read:

In the file operation we mainly use FileReader and FileWriter or BufferedReader and BufferedWriter.

From the class structure diagram:

FileReader is a subclass of InputStreamReader, and InputStreamReader is a subclass of reader;

FileWriter is a subclass of OutputStreamWriter, while OutputStreamWriter is the subclass of writer.

2.2. Use of FileReader and BufferedReader

The common structures of FileReader include the following two types:

(1) filereader (String filename): Creates a FileReader object from the file name.

(2) FileReader (file file): Creates a FileReader object from the file object.

Common methods of FileReader include the following:

(1) int read (): reads a single character. Returns the integer value of the character, or 1 if the end of the file has been reached.

(2) int read (char[] cbuf): reads characters into the cbuf character array. Returns the number of characters read to, or 1 if the end of the file has been reached.

(3) int read (char[] cbuf,int off,int len): holds the read character to the Cbuf character array starting at the offset from the off identity, reading up to Len characters.

BufferedReader has the following two methods of construction:

(1) BufferedReader (reader in): Creates an Bufferreader instance based on the Reader object represented in, the buffer size takes the default value.

(2) BufferedReader (Reader In,int SZ): Creates an BufferedReader instance based on the Reader object represented in, the buffer size takes the specified SZ value.

Common methods of BufferedReader include the following:

(1) int read (): Returns the integer value of the character, or 1 if the end of the file has been reached.

(2) int read (char[], int, int): holds the read character to the Cbuf character array starting at the offset from the off identity, reading up to Len characters.

(3) String ReadLine (): reads a line of text. The method encounters the following characters or the string considers the current line to end: ' \ n ' (newline character), ' \ R ' (carriage return), ' \ R ' (carriage return line). Returns a string that contains the contents of the row, does not contain any line terminators, and returns null if the end of the stream has been reached.

code example:

Package Java_io;import Java.io.BufferedReader;  Import Java.io.File;  Import java.io.FileNotFoundException;  Import Java.io.FileReader; Import java.io.IOException; Public classTestreader { Public Static void Main(string[] args) {Testreader Testreader =NewTestreader (); String Path ="C:\\users\\luoguohui\\desktop\\readertest.txt";         Testreader.readfilebyfilereader (path);     Testreader.readfilebybufferedreader (path); } Public void Readfilebyfilereader(String Path) {FileReader FileReader =NULL;Try{FileReader =NewFileReader (path);Char[] buf =New Char[1024x768];//1024 characters per read            inttemp =0; System. out. println ("Readfilebyfilereader execution Result:"); while(temp = Filereader.read (BUF))! =-1) {System. out. Print (NewString (BUF,0, temp)); } System. out. println (); }Catch(Exception e)        {E.printstacktrace (); }finally{///Like this I/O operation as far as possible finally ensure close            if(filereader!=NULL) {Try{Filereader.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }    } Public void Readfilebybufferedreader(String Path) {File File =NewFile (path);if(File.isfile ()) {BufferedReader BufferedReader =NULL; FileReader FileReader =NULL;Try{FileReader =NewFileReader (file); BufferedReader =NewBufferedReader (FileReader);                   String line = Bufferedreader.readline (); System. out. println ("Readfilebybufferreader execution Result:"); while(Line! =NULL) {System. out. println (line);                  line = Bufferedreader.readline (); }              }Catch(FileNotFoundException e)              {E.printstacktrace (); }Catch(IOException e)              {E.printstacktrace (); }finally{Try{Filereader.close ();                  Bufferedreader.close (); }Catch(IOException e)                  {E.printstacktrace (); }              }          }      } }

The above code uses the finally, about finally although it is not related to I/O, but here is to say:

1, regardless of the occurrence of wood anomalies, finally block code will be executed;

2, when there is return in the try and catch, finally will still execute;

3, finally is executed after the return of the expression after the operation (at this time does not return the value of the operation, but first to save the value to return, the pipe finally in the code, the return value will not change, still is the value of the previous saved), So the function return value is determined before the finally execution;

4, finally, it is best not to include return, or the program will exit early, the return value is not a try or catch in the saved return value.

ReaderTest.txt text content:

Execution Result:

2.3. Use of FileWriter and Bufferwriter

The following four types of FileWriter are commonly constructed:

(1) FileWriter (String filename): Creates a FileWriter object from the file name.

(2) FileWriter (String Filename,boolean Append): Creates a FileWriter object based on the file name, and the append parameter is used to specify whether to append the content after the original file.

(3) FileWriter (file file): Creates a FileWriter object from the file object.

(4) FileWriter (file File,boolean append): Creates a FileWriter object based on the file object, and the append parameter specifies whether to append the content after the original file.

Common methods of FileWriter include the following:

(1) void writer (int c): writes a single character to a file that represents a positive integer c.

(2) void writer (char[] cbuf): Writes a character array cbuf to a file.

(3) void writer (char[] cbuf,int off, in Len): writes a character array to a file cbuf a Len character starting at the offset position off.

(4) void writer (string str): Writes the string str to a file, note that this method does not wrap automatically after writing is complete.

(5) Void writer (string str,int off,int len): Writes the string str to a file, starting at position off and part of a substring of length len.

(6) Writer append (char c): Appends a single character C to the file.

(7) Writer append (charsequence csq): Appends a sequence of characters to a file that CSQ represents. Charsequence is an interface introduced from the JDK1.4 version, representing a readable sequence of character values that provides uniform read-only access to many different kinds of character sequences.

(8) Writer append (charsequence csq,int start,int end): Appends a sequence of csq characters to a file, starting at position start, and ending part of the end character.

(9) void Flush (): Refreshes the character output stream buffer.

() void Close (): Closes the character output stream.

BufferedWriter also has the following two types of construction methods:

(1) BufferedWriter (writer out): Creates an BufferedWriter instance based on the writer object represented by out, with a buffer size of default value.

(2) BufferedWriter (writer Out,int sz): Creates an BufferedWriter instance based on the writer object represented by out, the buffer size takes the specified SZ value.

Common methods of BufferedWriter include the following:

(1) void Close (): Closes the character output stream.

(2) void Flush (): Refreshes the character output stream buffer.

(3) void NewLine (): Writes a line of text.

(4) void write (char[] cbuf, int offset, int count): Writes a character array to a file cbuf the Len character from the offset position off.

(5) void write (int onechar): writes a single character.

(6) void write (string str, int offset, int count): Writes the string to the file str from position off, part of a substring of length len.

(7) The above methods are rewritten writer, and the method of inheriting from Java.io.Writer: writer append (char c), writer append (Charsequence csq), writer append ( Charsequence csq, int start, int end), void Write (char[] cbuf), write (String str), and so on.

code example:

 PackageJava_io;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportJava.io.FileWriter;ImportJava.io.IOException; Public  class testwriter {     Public Static void Main(string[] args) {Testwriter Testwriter =NewTestwriter (); String Path ="C:\\users\\luoguohui\\desktop\\readertest.txt";          Testwriter.writefilebyfilewriter (path);      Testwriter.writefilebybufferwriter (path); } Public void Writefilebyfilewriter(String Path) {FileWriter FileWriter =NULL;Try{FileWriter =NewFileWriter (Path,true);//Writes a string to the stream, \ r \ n indicates line break            //Because FileWriter does not wrap automaticallyFilewriter.write ("The bank is a line to join through FileWriter \ r \ n");//If you want to see the write effect immediately, you need to call the W.flush () methodFilewriter.flush (); }Catch(IOException e)          {E.printstacktrace (); }finally{if(FileWriter! =NULL) {Try{Filewriter.close (); }Catch(IOException e)                  {E.printstacktrace (); }              }          }      } Public void Writefilebybufferwriter(String Path) {File File =NewFile (path);if(File.isfile ()) {BufferedWriter BufferedWriter =NULL; FileWriter FileWriter =NULL;Try{FileWriter =NewFileWriter (file,true); BufferedWriter =NewBufferedWriter (FileWriter); Bufferedwriter.write ("The bank is a line to join through bufferedwriter \ r \ n");              Bufferedwriter.flush (); }Catch(FileNotFoundException e)              {E.printstacktrace (); }Catch(IOException e)              {E.printstacktrace (); }finally{Try{Filewriter.close ();                  Bufferedwriter.close (); }Catch(IOException e)                  {E.printstacktrace (); }              }          }      } }

We first empty the contents of the ReaderTest.txt file, the result of the operation is as follows (do not empty the line, just run the results of the blogger's different):

Three, the word stream instance

3.1. Before instance

Again, as mentioned earlier, "As long as you are dealing with plain text data, you should prioritize the use of character streams, in addition to the byte stream."

Here bloggers posted a character stream diagram structure, convenient for apes to read:

Below we still take file read and write as an example.

3.2, the use of FileInputStream

FileInputStream Method of Construction:

(1) FileInputStream (file file): Creates a fileinputstream by opening a connection to the actual file, which is specified by a file object in the filesystem.

(2) FileInputStream (FileDescriptor fdobj): Creates a fileinputstream by using the file descriptor Fdobj, which represents an existing connection to an actual file in the file system.

(3) FileInputStream (String name) creates a fileinputstream by opening a connection to the actual file, which is specified by the pathname name in the file system.

Common methods of FileInputStream:

(1) int available (): Returns the estimated number of remaining bytes that the next method invoked on this input stream can be read (or skipped) from this input stream in a blocked manner.

(2) void Close (): Closes this file input stream and frees all system resources related to this stream.

(3) protected void Finalize (): Make sure that the Close method is called when the file input stream is no longer referenced.

(4) FileChannel Getchannel (): Returns the unique FileChannel object associated with this file input stream.

(5) FileDescriptor getfd (): Returns a FileDescriptor object that represents the connection to the actual file in the file system, which is being used by this fileinputstream.

(6) int read (): reads a byte of data from this input stream.

(7) int read (byte[] b): reads up to b.length bytes of data from this input stream into a byte array.

(8) int read (byte[] b, int off, int len): reads up to len bytes of data from this input stream into a byte array.

(9) long Skip (long N): Skips and discards n bytes of data from the input stream.

code example:

Package Java_io;import Java.io.fileinputstream;import java.io.IOException; Public classTestfileinputstream { Public Static void Main(string[] args) {Testfileinputstream Testfileinputstream =NewTestfileinputstream (); String Path ="C:\\users\\luoguohui\\desktop\\readertest.txt";     Testfileinputstream.readfilebyfileinputstream (path); } Public void Readfilebyfileinputstream(String Path) {FileInputStream FileInputStream =NULL;Try{//create file input stream objectFileInputStream =NewFileInputStream (path);//Set the number of bytes read            intn =1024x768;byteBuffer[] =New byte[1024x768];//Read input streamSystem. out. println ("Readfilebyfileinputstream execution Result:"); while(Fileinputstream.read (Buffer,0, n)! =-1) && (n >0)) {System. out. Print (NewString (buffer)); } System. out. println (); }Catch(IOException IoE)        {Ioe.printstacktrace (); }Catch(Exception e)        {E.printstacktrace (); }finally{//Close input stream            if(FileInputStream! =NULL) {Try{Fileinputstream.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }    }}

ReaderTest.txt content:

Operation Result:

3.3, the use of FileOutputStream

FileOutputStream Method of Construction:

(1) FileOutputStream (file file): Creates an output stream that writes data to the file represented by the specified Files object.

(2) FileOutputStream (file file, Boolean append): Creates a file output stream that writes data to a file that is represented by the specified file object. The append parameter is used to specify whether to append content after the original file.

(3) FileOutputStream (FileDescriptor fdobj): Creates an output file stream that writes data to the specified file descriptor, which represents an existing connection to an actual file in the file system.

(4) FileOutputStream (String name): Creates an output file stream that writes data to a file with the specified name.

(5) FileOutputStream (String name, Boolean append): Creates an output file stream that writes data to a file with the specified name. The append parameter is used to specify whether to append content after the original file.

Common methods of FileOutputStream:

(1) void Close (): closes this output stream and frees all system resources related to this stream.

(2) void Flush (): refreshes this output stream and forces all buffered output bytes to be written out.

(3) void write (byte[] b): writes B.length bytes from a specified byte array to this output stream.

(4) void write (byte[] b, int off, int len): Writes the specified byte array of len bytes starting from offset off to this output stream.

(6) abstract void write (int b): Writes the specified bytes to this output stream.

code Example:

 PackageJava_io;ImportJava.io.FileOutputStream; Public  class testfileoutputstream {     Public Static void Main(string[] args) {Testfileoutputstream Testfileoutputstream =NewTestfileoutputstream (); String Path ="C:\\users\\luoguohui\\desktop\\readertest.txt";     Testfileoutputstream.readfilebyfileoutputstream (path); } Public void Readfilebyfileoutputstream(String Path) {FileOutputStream FOS =NULL;Try{fos =NewFileOutputStream (Path,true); String str ="This is what you added with FileOutputStream \ r \ n";byte[] B = str.getbytes ();              Fos.write (b);        Fos.flush (); }Catch(Exception e)        {E.printstacktrace (); }finally{Try{Fos.close (); }Catch(Exception E2)            {E2.printstacktrace (); }          }      }}

Operation Result:

Java I/O learning (with examples and explanations)

Related Article

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.