Java I/O-related content learning (with examples and details)

Source: Internet
Author: User

Java I/O-related content learning (with examples and details)
I. Basic concepts of Java I/O class structure and stream

Before reading Java I/O instances, we must understand some concepts. Let's first look at the class structure of Java I/O:

Java I/O mainly reads and writes data in the form of a stream.

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.

Data types can be divided into two types: traffic flow and word throttling.

The main differences between two types of throttling:

1. when a byte stream is read, one byte is returned when one byte is read. The byte stream uses the byte stream to read one or more bytes (the number of bytes corresponding to Chinese characters is two, in the UTF-8 code table is 3 bytes. First, check the specified encoding table and return the characters.

2. byte streams can process all types of data, such as image, MP3, and AVI Video files. The byte stream can only process character data. As long as it is processing plain text data, it is necessary to prioritize the use of byte streams, in addition to byte streams.

3. In fact, the byte stream itself does not use a buffer (memory) during operations, but directly operates on the file itself. The swap stream uses a buffer during operations and operates on the file through the buffer.

Next we will take file operations as an example to learn more.

Ii. Producer stream instance

As mentioned earlier, "as long as you are processing plain text data, you must first consider using the byte stream ". Therefore, this example is used to operate txt files. Perform read/write operations on it.

2.1 concepts

Previously, we needed to understand some concepts.

Java uses 16-bit Unicode to represent strings and characters. You can specify the encoding of the Written string when writing data to the upstream stream.

Here, the blogger posts the structure of the livestream graph to facilitate reading by yuanyou:

During file operations, we mainly use FileReader, FileWriter, BufferedReader, and BufferedWriter. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Signature + 0o7o8L3A + signature + PC9wPg0KPHA + signature/Signature + PC9wPg0KPHA + signature + w/Signature + b7dRmlsZbbUz/Signature + signature/Signature + 7XE1fvK/Signature + rbW9tO/OxLz + kernel/vK/kernel + kernel/WtaGjPC9wPg0KPHA + kernel + b7daW60 + rHttcRSZWFkZXK21M/kernel + release/release + release/C19a3 + 7vy1d/release + release/release + 6OsyOe5 + release + PHN0cm9uZz60 + sLryrXA/aO6PC9zdHJvbmc + PC9wPg0KPHByZSBjbGFzcz0 = "brush: java; "> Package java_io; import java. io. bufferedReader; import java. io. file; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. IOException; public class TestReader {public static void main (String [] args) {TestReader testReader = new TestReader (); String path = "C: \ Users \ luoguohui \ Desktop \ readerTest.txt "; testReader. readFileByFileReader (path); testReader. readFileByBuffered Reader (path);} public void readFileByFileReader (String path) {FileReader fileReader = null; try {fileReader = new FileReader (path); char [] buf = new char [1024]; // read 1024 characters each time int temp = 0; System. out. println ("readFileByFileReader execution result:"); while (temp = fileReader. read (buf ))! =-1) {System. out. print (new String (buf, 0, temp);} System. out. println ();} catch (Exception e) {e. printStackTrace ();} finally {// I/o operations like this try to finally ensure that if (fileReader! = Null) {try {fileReader. close ();} catch (IOException e) {e. printStackTrace () ;}}} public void readFileByBufferedReader (String path) {File file = new File (path); if (file. isFile () {BufferedReader bufferedReader = null; FileReader fileReader = null; try {fileReader = new FileReader (file); bufferedReader = new BufferedReader (fileReader); String line = bufferedReader. readLine (); System. out. p Rintln ("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 finally. Although finally has nothing to do with I/O, let's talk about it here:

1. Code in finally blocks will be executed no matter there is an exception in wood;

2. If return exists in try and catch, finally will still execute;

3. finally is executed after the expression operation after return (the value after return is not returned at this time, but the value to be returned is saved first, regardless of the Code in finally, the returned values will not change, or are previously saved values). Therefore, the return value of the function is determined before finally execution;

4. It is best not to include return in finally; otherwise, the program exits early and the return value is not the value saved in try or catch.

ReaderTest.txt text content:

Execution result:

2.3 use of FileWriter and BufferWriter

FileWriter has the following structures:

(1) FileWriter (String fileName): Creates a FileWriter object based on the file name.

(2) 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.

(3) FileWriter (File file): Creates a FileWriter object based on the File object.

(4) 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:

(1) void writer (int c): write a single character represented by positive integer c to the file.

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

(3) void writer (char [] cbuf, int off, in len): Write the len characters starting from the off position of the character array cbuf to the file.

(4) 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 complete.

(5) void writer (String str, int off, int len): Write A Part Of The substring of the String str to the file starting from position off and length is len.

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

(7) 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.

(8) Writer append (CharSequence csq, int start, int end): append a part of the csq Character Sequence starting from position start and ending to the file.

(9) void flush (): refresh the character output stream buffer.

(10) void close (): close the character output stream.

BufferedWriter also has the following constructor methods:

(1) BufferedWriter (Writer out): Creates a BufferedWriter instance based on the Writer object represented by "out". The buffer size uses the default value.

(2) BufferedWriter (Writer out, int sz): Creates a BufferedWriter instance based on the Writer object represented by out. The buffer size uses the specified sz value.

BufferedWriter provides the following common methods:

(1) void close (): close the character output stream.

(2) void flush (): refresh the character output stream buffer.

(3) void newLine (): write text lines.

(4) void write (char [] cbuf, int offset, int count): write the len characters starting from the off position of the character array cbuf to the file.

(5) void write (int oneChar): write a single character.

(6) void write (String str, int offset, int count): write A Part Of The substring of the String str to the file starting from the off position and the length is len.

(7) The above methods both overwrite Writer and inherit from java. io. writer method: Writer append (char c), Writer append (CharSequence csq), Writer append (CharSequence csq, int start, int end), void write (char [] cbuf) and write (String str.

Code example:

Package java_io; import java. io. bufferedWriter; import java. io. file; import java. io. fileNotFoundException; import java. io. fileWriter; import java. io. IOException; public class TestWriter {public static void main (String [] args) {TestWriter testWriter = new TestWriter (); String path = "C: \ Users \ luoguohui \ Desktop \ readerTest.txt "; testWriter. writeFileByFileWriter (path); testWriter. writeFileByBufferWrite R (path);} public void writeFileByFileWriter (String path) {FileWriter fileWriter = null; try {fileWriter = new FileWriter (path, true); // write the String to the stream, \ r \ n indicates line feed // because fileWriter does not automatically wrap fileWriter. write ("the row is added through fileWriter \ r \ n"); // if you want to see the write effect immediately, you need to call w. flush () method fileWriter. 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 = new File (path); if (file. isFile () {BufferedWriter bufferedWriter = null; FileWriter fileWriter = null; try {fileWriter = new FileWriter (file, true); bufferedWriter = new BufferedWriter (fileWriter); bufferedWriter. write ("this row is added 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 ();}}}}}

First, we need to clear the content of the readertest.txt file. The running result is as follows (not empty, but the result is different from that of the blogger ):

Iii. byte stream instance

3.1. Before the instance

Again, we have mentioned that "as long as you are processing plain text data, you need to prioritize the use of byte streams, in addition to byte streams ".

Here, the blogger posts the byte stream graph structure to facilitate reading by yuanyou:

The following uses file read/write as an example.

3.2 use of FileInputStream

FileInputStream constructor:

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

(2) FileInputStream (FileDescriptor fdObj): Creates a FileInputStream by using the file descriptor fdObj, which indicates 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 path name in the file system.

Common FileInputStream methods:

(1) int available (): returns the estimated number of remaining bytes that can be read (or skipped) from the input stream without blocking the method called for this input stream.

(2) void close (): close the input stream of this file and release all system resources related to this stream.

(3) protected void finalize (): Make sure to call the close method when the file input stream is no longer referenced.

(4) FileChannel getChannel (): returns the unique FileChannel object related to the input stream of the file.

(5) FileDescriptor getFD (): returns the FileDescriptor object indicating the actual file connected to the file system. The file system is being used by this FileInputStream.

(6) int read (): read a Data byte from the input stream.

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

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

(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 class TestFileInputStream {public static void main (String [] args) {TestFileInputStream testFileInputStream = new TestFileInputStream (); String path = "C: \ Users \ luoguohui \ Desktop \ readerTest.txt "; testFileInputStream. readFileByFileInputStream (path);} public void readFileByFileInputStream (String path) {FileInputSt Ream fileInputStream = null; try {// create a file input stream object fileInputStream = new FileInputStream (path); // set the number of bytes read int n = 1024; byte buffer [] = new byte [1024]; // read the input stream System. out. println ("readFileByFileInputStream execution result:"); while (fileInputStream. read (buffer, 0, n )! =-1) & (n> 0) {System. out. print (new String (buffer);} System. out. println ();} catch (IOException ioe) {ioe. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {// close the input stream if (fileInputStream! = Null) {try {fileInputStream. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

ReaderTest.txt content:

Running result:

3.3 Use of FileOutputStream

FileOutputStream constructor:

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

(2) FileOutputStream (File file, boolean append): Creates a File output stream that writes data to the File 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 a specified file descriptor. This file descriptor 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 a specified name.

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

Common FileOutputStream methods:

(1) void close (): close the output stream and release all system resources related to the stream.

(2) void flush (): refresh the output stream and forcibly write all buffered output bytes.

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

(4) 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.

(6) abstract void write (int B): write the specified byte to this output stream.

Code example:

Package java_io; import java. io. fileOutputStream; public class TestFileOutputStream {public static void main (String [] args) {TestFileOutputStream testFileOutputStream = new TestFileOutputStream (); String path = "C: \ Users \ luoguohui \ Desktop \ readerTest.txt "; testFileOutputStream. readFileByFileOutputStream (path);} public void readFileByFileOutputStream (String path) {FileOutputStream fos = null; try {fos = new FileOutputStream (path, true ); string str = "this is the content added using 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 ();}}}}

Running result:

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.