Java I/O interpretation and usage examples

Source: Internet
Author: User
Tags file copy

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Abstract: This article mainly explains the Java I/O interpretation and use examples.

I. Basic concepts of I/O

I/O full name is Input/output,java I/O is Java input and output operation. The interfaces and classes associated with it are placed inside the java.io package, so you need to import the package for Java input and output operations. Using Java I/O greatly expands the input and output categories of the system, not only input and output from the console, but also input and output from other data storage, such as local files, remote databases, etc. Java I/O plays an important role in the reading and writing of file data, the network sending and receiving of data, and many other occasions.


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. There are two main types of operations for file content: character stream and Byte stream

(1) Byte stream has two abstract class: InputStream outputstream its corresponding subclass has FileInputStream and FileOutputStream realize file reading and writing. The Bufferedinputstream and Bufferedoutputstream provide buffer functionality.



(2) Character Stream has two abstract classes: Writer reader its corresponding subclass FileWriter and FileReader can realize the file read and write operation. BufferedWriter and BufferedReader can provide buffer functions to improve efficiency.



Ii. Classification of I/O streams

Divided into: character stream and byte stream according to different types of processing data
Divided into: input stream and output stream according to data flow
Character Stream and Byte stream
The origin of a character stream: Because of the difference in data encoding, there is a stream object that efficiently operates on characters. The essence is actually based on the byte stream reading, to check the specified code table. The difference between a byte stream and a character stream:
(1) Different reading and writing units: Byte stream in bytes (8bit), character stream in characters, according to the Code table mapping characters, can read multiple bytes at a time.
(2) The processing object is different: The byte stream can handle all kinds of data (slices, AVI, etc.), while the character stream can only handle data of the type of characters.
(3) Byte stream in the operation of the time itself is not used in the buffer, is the direct operation of the file itself, and the character stream in the operation of the time after the buffer will be used, is through the buffer to manipulate the file, we will verify this below.
Conclusion: It is preferred to select byte stream. First, because all the files on the hard disk are transferred or saved in bytes, including images and so on. But characters are only formed in memory, so in development, the byte stream is used extensively.
Input stream and output stream
The input stream can only be read, the output stream can only write operations, the program needs to be transmitted according to the different characteristics of the data to use different streams.

Third, the byte stream reads and writes the operation 3.1, reads the file by the byte throttle

InputStream

This abstract class is a superclass of all classes that represent the byte input stream. Applications that need to define inputstream subclasses must always provide a way to return the next input byte.
int available ()
Returns the number of bytes that the next caller of this input stream method can read (or skip) from this input stream in a blocked manner.
void Close ()
Closes this input stream and frees all system resources associated with the stream.
void mark (int readlimit)
Marks the current position in this input stream.
Boolean marksupported ()
Tests whether this input stream supports the mark and reset methods.
abstract int Read ()
Reads the next data byte from the input stream.
int read (byte[] b)
Reads a certain number of bytes from the input stream and stores it in buffer array B.
int read (byte[] b, int off, int len)
Reads up to Len data bytes in the input stream into a byte array.
void Reset ()
Relocate this stream to the location when the mark method was last called on this input stream.
Long Skip (long N)
Skipping and discarding n bytes of data in this input stream

The class diagram is as follows:


Examples of usage are as follows:

Package Com.lin;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.ioexception;import java.io.inputstream;/** * Feature summary: Byte stream Read file * * @author Linbingwen * @since September 5, 2015 */public clas s Test1 {/** * @author Linbingwen * @since September 5, 2015 * @param args * @throws ioexception */public static void Main (string[    ] args) {String path = "D:" + file.separator + "Test1.txt"; readFile1 (path); readFile2 (path);} /** * Byte stream read file: Single character read * @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 ("=============================== single character read begin==============================="); int ch = 0;while ( (ch = is.read ())! =-1) {System.out.print ((char) ch);} System.out.println (); System.out.println ("=============================== single character read end===============================");} catch (IOException e) {e.printstacktrace ();} finally {//close input stream if (is! = null) {Try {is.close ();} catch (IOException e) {e.printstacktrace ();}}}} /** * Byte stream read file: Array loop read * @author Linbingwen * @since September 5, 2015 * @param path */public static void read File2 (String path) {FileInputStream is = null;try {//create file input Stream object is = new FileInputStream (path);//sets the number of bytes read int n = 512;byte buffer[] = new byte[n];//read 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 reads end===============================");}  catch (IOException IoE) {System.out.println (IoE);} catch (Exception e) {System.out.println (e);} finally {//turn off input stream if (is! = NULL) {try {is.close ();} catch (IOException e) {e.printstacktrace ()}}}}

Test1.txt content is as follows:



Program Run Result:


Note: For Chinese characters, characters are garbled and Chinese characters are read with a character stream.

If you change the content to read as follows:



The output results are as follows:


As you can see, Chinese does become garbled, which is the disadvantage of reading by byte.

3.2. write files by byte stream

OutputStream
This abstract class is a superclass of all classes that represent the output byte stream. The output stream accepts output bytes and sends those bytes to a sink. Applications that need to define outputstream subclasses must always provide at least one way to write an output byte.
void Close ()
Closes this output stream and frees all system resources related to this stream.
void Flush ()
Refreshes this output stream and forces all buffered output bytes to be written out.
void Write (byte[] b)
Writes a b.length byte from the specified byte array to this output stream.
void Write (byte[] b, int off, int len)
Writes Len bytes from offset off in the specified byte array to this output stream.
abstract void Write (int b)
Writes the specified bytes to this output stream.
I/O exceptions may be generated when I am doing I/OS, which are non-runtime exceptions and should be handled in the program. such as: FileNotFoundException, eofexception, IOException, etc., the following specific instructions to operate the Java byte stream method.

The class diagram is as follows:


Examples of usage are as follows:

Package Com.lin;import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;/** * Feature Summary: * * @ Author Linbingwen * @since September 5, 2015 */public class Test2 {/** * @author Linbingwen * @since September 5, 2015 * @param args */PUB Lic 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, can be picture, text * @author Linbingwen * @since September 5, 2015 * @param input * @param output */public static void Write File (string input, string output) {FileInputStream FIS = null; FileOutputStream fos = null;byte[] buffer = new Byte[100];int temp = 0;try {fis = new FileInputStream (input); fos = new Fil Eoutputstream (output), while (true) {temp = fis.read (buffer, 0, buffer.length), if (temp = =-1) {break;} Fos.write (buffer, 0, temp);}} catch (Exception e) {System.out.println (e);} finally {try {fis.close (); Fos.close ();} catch (Exception E2) { SYSTEM.OUT.PRINTLN (E2);}}}
Operation Result:


Also can carry on the MP3 write!

Four, character stream read and write operation 4.1, character Stream read operation

Java uses 16-bit Unicode to represent strings and characters, and the corresponding data stream is called a character stream. Reader and writer are designed for character streams. FileReader is a subclass of InputStreamReader, and InputStreamReader is a subclass of reader; FileWriter is a subclass of OutputStreamWriter, And OutputStreamWriter is the subclass of writer. The difference between a character stream and a byte stream is that the character stream operation object is an array of characters and characters, and the byte-stream operation object is an array of bytes and bytes.
character input stream
Common constructs of FileReader include the following.
FileReader (String filename): Creates a FileReader object based on the file name.
FileReader (File file): Creates a FileReader object from the file object.
common methods of FileReader include the following.
int read (): reads a single character. Returns the integer value of the character, or 1 if the end of the file has been reached.
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.
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.
Unlike the byte stream, Bufferreader is a direct subclass of reader, which is different from the class two subclass of Bufferinputstream InputStream. Through the Bufferreader.readline () method can be implemented to read the text line, return string, because we usually read the text file is mostly line-breaking, and the method can directly return the string, so bufferreader used more widely than filereader.
Bufferreader has the following two methods of construction.
Bufferreader (Reader in): Creates an Bufferreader instance from the Reader object represented by in, the buffer size takes the default value.
Bufferreader (Reader In,int SZ): Creates an Bufferreader instance based on the Reader object represented in, the buffer size takes the specified SZ value.
The Bufferreader.readline () 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.

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;/** * Feature Summary: Character Stream read operation * * @author Linbingwen * @since September 5, 2015 */public class Test3 {/** * @autho R Linbingwen * @since September 5, 2015 * @param args */public static void main (string[] args) {String path = "D:" + File.separato    R + "Test3.txt"; readFile1 (path); readFile2 (path); ReadFile3 (Path, "Utf-8");} /** * Character Stream Read File method one * @author Linbingwen * @since September 5, 2015 * @param path */public static void ReadFile1 (String path) {file Reader r = null;try {r = new FileReader (path);//optimization of the character array read-in//in that sometimes the file is too large to determine the size of the array that needs to be defined//So the general definition array length is 1024, which is read in a circular way char[] B UF = new Char[1024];int temp = 0; System.out.println ("========================== character stream reads file method one =========================="); 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 ();}}}}  /** * Character Stream Read File method two * @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); BufferedReader = new BufferedReader (FileReader); String line = Bufferedreader.readline (); System.out.println ("========================== character stream read file method two =========================="); while (line! = null) { System.out.println (line), Sb.append (line + "\ r \ n"); 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 ();} /** * Character Stream Read file: can specify file encoding format * @author Linbingwen * @since 2015 year September 5 * @param path * @param 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); BufferedReader = new BufferedReader (InputStreamReader); String line = Bufferedreader.readline (); System.out.println ("========================== character stream reads the file method three =========================="); while (line! = null) { System.out.println (line), Sb.append (line + "\ r \ n"); 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 ();}}
This is the result of the operation:


The third method, if you specify the encoding, results in the following:
ReadFile3 (Path, "GBK");

As you can see, Chinese has become garbled. 4.2. Write by charactercharacter output stream the common structures of filewriter are as follows.
FileWriter (String filename): Creates a FileWriter object based on the file name.
FileWriter (String Filename,boolean Append): Creates a FileWriter object from a file name, and the append parameter is used to specify whether to append the content after the original file.
FileWriter (File file): Creates a FileWriter object from the file object.
FileWriter (File File,boolean append): Creates a FileWriter object from the file object, and the append parameter specifies whether to append the content after the original file.
common methods of FileWriter include the following.
void writer (int c): writes a single character to a file that represents a positive integer c.
void writer (char[] cbuf): Writes a character array cbuf to a file.
void writer (char[] cbuf,int off, in Len): writes a character array to a file cbuf the Len character from the offset position off.
void writer (string str): Writes the string str to a file, noting that this method does not wrap automatically after writing.
void writer (string str,int off,int len): Writes a string to a file str from position off, part of a substring of length len.
Writer append (char c): Appends a single character C to a file.
Writer Append (charsequence csq): Appends a sequence of characters to a file that the 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.
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.
void Flush (): Refreshes the character output stream buffer.
void Close (): Closes the character output stream.
As opposed to Bufferreader, the Bufferwriter with the buffer enabled also has two forms of construction.
Bufferwriter (writer out): Creates an Bufferwriter instance based on the writer object represented by out, with a default buffer size.
Bufferwriter (writer Out,int sz): Creates an Bufferwriter instance based on the writer object represented by out, with a buffer size of the specified SZ value.
We know that the ReadLine () method of the Bufferreader class can read one line from the input stream at a time, but for the Bufferwriter class, there is no way to write one line at a time. To write one line at a time to the output stream, you can use the PrintWriter class (PrintWriter is also the direct subclass of writer) to change the original stream into a new print stream, PrintWriter class has a method println (String), can output one line at a time, That is, the string to be output automatically complements the "\ r \ n". Its 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 Summary: * * @author Linbingwen * @since September 5, 2015 */public class Test4 {/** * @author Linbingwe n * @since September 5, 2015 * @param args */public static void main (string[] args) {String path = "D:" + File.separator + " Test4.txt "; String str= "Evankaka Lin Bingwen evankaka Lin Bingwen evankaka Lin Bingwen \ r \ n"; WriteFile (PATH,STR); WriteFile (PATH,STR); WriteFile (PATH,STR);} /** * Write a file using a character stream * @author Linbingwen * @since September 5, 2015 * @param path * @param content */public static void WriteFile (St        Ring path,string content) {//Because the IO operation throws an exception, the reference to the FileWriter is defined outside the TRY statement block FileWriter w = null; try {//Create a new FileWriter object with path =//If you need to append data instead of overwriting, use FileWriter (path,true) Construction Method//w = new Fi                  Lewriter (path,true);                       w = new FileWriter (path,true);            Writes a string to the stream, \ r \ n indicates a newline w.write (content);    If you want to see the write effect immediately, you need to call the W.flush () method        W.flush ();        } catch (IOException e) {e.printstacktrace ();  } finally {///If an exception occurs before, the W object cannot be produced//so be judged to avoid a null pointer exception if (w! = null) {try                {//Close stream resource, need to catch Exception w.close () again;                } catch (IOException e) {e.printstacktrace (); }            }        }}}

The contents of the file are written as follows:
Reference article: http://developer.51cto.com/art/201309/410902.htmhttp://www.ibm.com/developerworks/cn/java/j-lo-javaio/

Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, reproduced please indicate the source Http://blog.csdn.net/evankaka

Java I/O interpretation and usage examples

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.