Java I/O interpretation and use example

Source: Internet
Author: User

Java I/O interpretation and use example

 

Abstract: This article describes how to interpret and use Java I/O.

I. Basic concepts of I/O

The full name of I/O is Input/Output, and Java I/O is the Input and Output operations of Java. Related interfaces and classes are stored in the java. io package. Therefore, you need to import the package during Java input and output operations. Java I/O greatly extends the input and output categories of the system, not only from the console, but also from other data storage formats, such as local files and remote databases. Java I/O plays an important role in reading, writing, and receiving file data.

A stream is a set of sequential bytes with a starting point and an ending point. It is a general term or abstraction for data transmission. That is to say, the transmission of data between two devices is called a stream. The essence of a stream is data transmission. Based on the data transmission characteristics, the stream is abstracted into various types to facilitate more intuitive data operations. There are two main types of file content operations: traffic flow and word throttling.

(1) The byte stream has two abstract classes: InputStream OutputStream and its corresponding sub-classes include FileInputStream and FileOutputStream for file read and write. BufferedInputStream and BufferedOutputStream provide the buffer function.

 



(2) The primary stream has two abstract classes: Writer Reader and its corresponding sub-classes FileWriter and FileReader can perform file read/write operations. BufferedWriter and BufferedReader can provide the buffer function to improve efficiency.

 

II. I/O stream classification

Data types can be divided into two types: dense stream and word throttling.
Data flows are divided into input streams and output streams.
Traffic and word throttling
The origin of the character stream: because of the different data encoding, there is a stream object for efficient character operations. In essence, when reading data based on byte streams, the specified code table is checked. Differences between byte stream and byte stream:
(1) Different read/write units: byte streams are measured in 8 bits, and the byte streams are measured in characters. Based on the ing characters in the code table, multiple bytes may be read at a time.
(2) Different processing objects: byte streams can process all types of data (such as slice and avi), while the byte stream can only process character-type data.
(3) The byte stream itself does not use the buffer zone during operations, but directly operates the file itself. The swap stream will use the buffer zone after the operation, is to operate the file through the buffer, We will verify this in the following.
Conclusion: byte streams are preferred. First, because all files on the hard disk are transmitted or saved in bytes, including images and other content. However, characters are only formed in the memory. Therefore, byte streams are widely used during development.

Input stream and output stream
Only read operations can be performed on the input stream, and only write operations can be performed on the output stream. Different streams must be used in the program based on different features of the data to be transmitted.

Iii. byte stream read/write operations 3.1. Reading files by byte stream

InputStream

This abstract class is a super class that represents all classes of the byte input stream. Applications that need to define the subclass of InputStream must always provide the method to return the next input byte.
Int available ()
Returns the number of bytes that the next caller of the input stream method can read (or skip) from the input stream without blocking.
Void close ()
Close the input stream and release all system resources associated with the stream.
Void mark (int readlimit)
Mark the current position in the input stream.
Boolean markSupported ()
Test whether the input stream supports the mark and reset methods.
Abstract int read ()
Reads the next Data byte from the input stream.
Int read (byte [] B)
Read a certain number of bytes from the input stream and store them in the buffer array B.
Int read (byte [] B, int off, int len)
Reads a maximum of len data bytes from the input stream into the byte array.
Void reset ()
Locate the stream again when the mark method is called for the input stream.
Long skip (long n)
Skip and discard n data bytes in the input stream

The class diagram is as follows:

Example:

 

Package com. lin; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. io. inputStream;/*** function Overview: byte stream File Reading ** @ author linbingwen * @ since September 5, 2015 */public class Test1 {/*** @ author linbingwen * @ since September 5, 2015 * @ param args * @ throws IOException */ public static void main (String [] args) {String path = D: + File. separator + te St1.txt; readFile1 (path); readFile2 (path);}/*** byte stream to read files: read a single character * @ author linbingwen * @ since September 5, 2015 * @ param path */public static void readFile1 (String path) {FileInputStream is = null; try {is = new FileInputStream (path); System. out. println (=================================== reading a single character begin ====== ============================ ); int ch = 0; while (ch = is. read ())! =-1) {System. out. print (char) ch);} System. out. println (); System. out. println (================================ read end = for a single character ============================ );} catch (IOException e) {e. printStackTrace ();} finally {// close the input stream if (is! = Null) {try {is. close ();} catch (IOException e) {e. printStackTrace () ;}}}/*** byte stream to read files: array loop read * @ author linbingwen * @ since September 5, 2015 * @ param path */public static void readFile2 (String path) {FileInputStream is = null; try {// create a file input stream object is = new FileInputStream (path); // set the number of bytes read int n = 512; byte buffer [] = new byte [n]; // read the input stream System. out. println (=============================== array loop read begin ==== ========== ======================); While (is. read (buffer, 0, n )! =-1) & (n> 0) {System. out. print (new String (buffer);} System. out. println (); System. out. println (================================= array loop read end ==== ============================ );} catch (IOException ioe) {System. out. println (ioe);} catch (Exception e) {System. out. println (e);} finally {// close the input stream if (is! = Null) {try {is. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

The content of test1.txt is as follows:

 

 

Program running result:

Note: Garbled characters may occur for Chinese characters. The Chinese characters must be read using the character stream.

If you change the content to the following:

 

The output result is as follows:

We can see that Chinese characters are indeed garbled, which is the disadvantage of byte reading.

3.2 write files in byte streams

OutputStream
This abstract class is a super class that represents all the classes of the output byte stream. The output stream accepts the output bytes and sends them to a receiver. Applications that need to define the OutputStream subclass must always provide at least one method that can write one output byte.
Void close ()
Close the output stream and release all system resources related to the stream.
Void flush ()
Refresh the output stream and forcibly write all buffered output bytes.
Void write (byte [] B)
Write B. length bytes from the specified byte array to this output stream.
Void write (byte [] B, int off, int len)
Write the len bytes starting from offset off in the specified byte array to this output stream.
Abstract void write (int B)
Write the specified byte to the output stream.
I/O exceptions may be generated during I/O operations, which are non-runtime exceptions and should be processed in the program. For example: FileNotFoundException, EOFException, IOException, etc. The following describes how to operate a JAVA byte stream.

The class diagram is as follows:

Example:

 

Package com. lin; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream;/*** function Overview: ** @ author linbingwen * @ since September 5, 2015 */public class Test2 {/*** @ author linbingwen * @ since September 5, 2015 * @ param args */public static void main (String [] args) {String input = D: + File. separator + hello.jpg; String output = D: + File. separator + hello1.jpg; writeFile (input, output);}/*** file copy operation, it can be an image or text ** @ author linbingwen * @ since September 5, 2015 * @ param input * @ param output */public static void writeFile (String input, String output) {FileInputStream FCM = null; FileOutputStream fos = null; byte [] buffer = new byte [100]; int temp = 0; try {FD = new FileInputStream (input ); fos = new FileOutputStream (output); while (true) {temp = FCM. read (buffer, 0, buffer. length); if (temp =-1) {break;} fos. write (buffer, 0, temp) ;}} catch (Exception e) {System. out. println (e);} finally {try {FCM. close (); fos. close ();} catch (Exception e2) {System. out. println (e2 );}}}}
Running result:

 

 


 

You can also write MP3 files!

Iv. Upstream stream read/write operations 4.1 and upstream stream read Operations

Java uses 16-bit Unicode to represent strings and characters. The corresponding data stream is called the bytes stream. Reader and Writer are designed for internal streams. FileReader is a subclass of InputStreamReader, while InputStreamReader is a subclass of Reader, FileWriter is a subclass of OutputStreamWriter, and OutputStreamWriter is a subclass of Writer. The difference between upstreaming and word Throttling is that the object of upstreaming operations is a character and character array, while the object of byte stream operations is a byte and byte array.
Character input stream
Common structures of FileReader include.
FileReader (String fileName): Creates a FileReader object based on the file name.
FileReader (File file): Creates a FileReader object based on the File object.
Common FileReader methods include.
Int read (): read a single character. Returns the integer of the character. If it has reached the end of the file,-1 is returned.
Int read (char [] cbuf): reads characters into the cbuf character array. Returns the number of characters read. If the number has reached the end of the file,-1 is returned.
Int read (char [] cbuf, int off, int len): stores the read characters in the cbuf character array starting from the offset of the off mark, and reads a maximum of len characters.
Unlike byte streams, BufferReader is the direct subclass of Reader, which is different from BufferInputStream's second-level subclass of InputStream. Through BufferReader. the readLine () method can read lines of text and return strings, because most of the text files we read at ordinary times are broken lines, and this method can directly return strings, therefore, BufferReader is more widely used than FileReader.
BufferReader adopts the following two constructor methods.
BufferReader (Reader in): Creates a BufferReader instance based on the Reader object represented by in. The buffer size uses the default value.
BufferReader (Reader in, int sz): Creates a BufferReader instance based on the Reader object represented by in. The buffer size uses the specified sz value.
The BufferReader. readLine () method encounters the following character or string that the current row ends: ''(line feed),'' (carriage return), ''(carriage return line feed ). The return value is a string of the row content and does not contain any line terminator. If it has reached the end of the stream, null is returned.

The class diagram is as follows:

The instance code is as follows:

 

Package com. lin; import java. io. bufferedReader; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. IOException; import java. io. inputStreamReader;/*** function Overview: merge stream read operation ** @ author linbingwen * @ since September 5, 2015 */public class Test3 {/*** @ author linbingwen * @ since September 5, 2015 * @ param args */public static void main (string [] args) {String path = D: + File. separator + test3.txt; readFile1 (path); readFile2 (path); readFile3 (path, UTF-8 );} /*** method 1 for reading objects from the streams * @ author linbingwen * @ since September 5, 2015 * @ param path */public static void readFile1 (String path) {FileReader r = null; try {r = new FileReader (path); // read to character array optimization // sometimes because 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. The char [] buf = new char [1024] is read cyclically; int temp = 0; System. out. println (= = ================ ); While (temp = r. read (buf ))! =-1) {System. out. print (new String (buf, 0, temp);} System. out. println ();} catch (IOException e) {e. printStackTrace ();} finally {if (r! = Null) {try {r. close ();} catch (IOException e) {e. printStackTrace ();}}}} /*** method 2 for reading a file from a streams * @ author linbingwen * @ since September 5, 2015 * @ param path * @ return */public static String readFile2 (String path) {File file = new File (path); StringBuffer sb = new StringBuffer (); if (file. isFile () {BufferedReader bufferedReader = null; FileReader fileReader = null; try {fileReader = new FileReader (file); bufferedRea Der = new BufferedReader (fileReader); String line = bufferedReader. readLine (); System. out. println (================================ method 2 of the pipeline stream File Reading ========== ========================== ); while (line! = Null) {System. out. println (line); sb. append (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 () ;}} return sb. toString ();}/*** allow stream to read files: You can specify the file encoding format * @ author linbingwen * @ since September 5, 2015 * @ param path * @ para M charset * @ return */public static String readFile3 (String path, String charset) {File file = new File (path); StringBuffer sb = new StringBuffer (); if (file. isFile () {BufferedReader bufferedReader = null; InputStreamReader inputStreamReader = null; try {inputStreamReader = new InputStreamReader (new FileInputStream (file), charset); shard = new bufferedReader (inputStreamReader ); string line = bu FferedReader. readLine (); System. out. println (================================== method 3 of the pipeline stream File Reading ======== ========================== ); while (line! = Null) {System. out. println (line); sb. append (line +); line = bufferedReader. readLine () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {inputStreamReader. close (); bufferedReader. close ();} catch (IOException e) {e. printStackTrace () ;}} return sb. toString ();}}
Here is the running result:

 

If encoding is specified in the third method, the result is as follows:
readFile3(path,GBK);

As you can see, Chinese characters are garbled. 4.2 write character output streams by character FileWriter has the following common structures.
FileWriter (String fileName): Creates a FileWriter object based on the file name.
FileWriter (String fileName, boolean append): Creates a FileWriter object based on the file name. The append parameter is used to specify whether to append content after the original file.
FileWriter (File file): Creates a FileWriter object based on the File object.
FileWriter (File file, boolean append): Creates a FileWriter object based on the File object. The append parameter is used to specify whether to append content after the original File.
FileWriter uses the following methods.
Void writer (int c): write a single character represented by positive integer c to the file.
Void writer (char [] cbuf): writes a character array cbuf to the file.
Void writer (char [] cbuf, int off, in len): The len characters starting from the off position of the cbuf string written to the file.
Void writer (String str): writes the str String to the file. Note that this method will not automatically wrap the String after the write is completed.
Void writer (String str, int off, int len): Write A Part Of The substring of the String 'str' from the position 'off' to the file and its length is 'len.
Writer append (char c): append a single character c to the file.
Writer append (CharSequence csq): append a character sequence represented by csq to the file. CharSequence is an interface introduced from JDK1.4, representing a readable sequence of character values. This interface provides unified read-only access to many different types of character sequences.
Writer append (CharSequence csq, int start, int end): append a part of the csq Character Sequence from position start and end to the file.
Void flush (): refresh the character output stream buffer.
Void close (): close the character output stream.
As opposed to BufferReader, the buffer-enabled BufferWriter also has two forms of constructor.
BufferWriter (Writer out): Creates a BufferWriter instance based on the Writer object represented by out. The buffer size defaults.
BufferWriter (Writer out, int sz): Creates a BufferWriter instance based on the Writer object represented by out. The buffer size uses the specified sz value.
We know that the readLine () method of the BufferReader class can read a row from the input stream at a time, but there is no way to write a row at a time for the BufferWriter class. To write a row to the output stream at a time, use the PrintWriter class (PrintWriter is also the direct subclass of Writer) to transform the original stream into a new print stream, the PrintWriter class has a method println (String) that can output a row at a time, that is, it automatically fills in "" after the String to be output. the class diagram is as follows:
The instance code is as follows:
Package com. lin; import java. io. bufferedWriter; import java. io. file; import java. io. fileWriter; import java. io. IOException;/*** function Overview: ** @ author linbingwen * @ since September 5, 2015 */public class Test4 {/*** @ author linbingwen * @ since September 5, 2015 * @ param args */public static void main (String [] args) {String path = D: + File. separator + test4.txt; String str = Evankaka Lin bingwen; writeFile (path, Str); writeFile (path, str); writeFile (path, str );} /*** use the upload stream to write files * @ author linbingwen * @ since September 5, 2015 * @ param path * @ param content */public static void writeFile (String path, String content) {// The IO operation throws an exception. Therefore, the reference FileWriter w = null is defined externally in the try statement block; try {// create a new FileWriter object using path. // use FileWriter (path, true) If data needs to be appended instead of overwritten) constructor // w = new FileWriter (path, true); w = new FileWriter (path, true ); // Write the string into the stream, which indicates the line feed w. write (content); // if you want to see the write effect immediately, you need to 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 ();}}}}}

The content of the written file is as follows:
 

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.