Java in IO stream consolidation Learning 1

Source: Internet
Author: User
Tags exception handling flushes

Overall classification diagram in 1.java flow



Other common flow-related objects:


2.IO Flow

IO flow: Primarily for processing data on devices

Such as: Hard disk, memory, keyboard input


IO has a specific classification: 1. Depending on the type of processing data: byte stream and character streams. 2. According to different flow: input flow and output flow

The origin of character streams: Because files are encoded differently, there is a character stream object that efficiently operates on characters.

Principle: In fact, is based on the byte stream to read bytes, to check the specified encoding table.


The difference between a stream of bytes and a character:

1. When a byte stream is read, it returns a byte when it is read. The character stream reads one or more bytes using a byte (Chinese corresponding byte city two, in the UTF-8 encoded table is 3 bytes), first to check the specified encoding table, will be found in the characters returned.

2. The byte stream can handle all the data types, such as Mp3,avi. A character stream can only handle characters data.

Conclusion: As long as the character stream is given priority in pure text, all the other words are throttled.


The basic functions of IO System: Reading and writing

1. Byte stream: InputStream (Read), OutputStream (write)

2. Character streams: Reader (read), Writer (write)


Basic read and write operation mode:

Because the data is usually in the form of a file, it is necessary to find a stream object in the IO system that can be used to manipulate files. It is easier to get objects by name, because the subclass name suffixes in the IO system are mostly the names of the parent classes, and the prefixes are the names that embody the function of the subclass.

Reader "-----------InputStreamReader"-------------FileReader: A character stream specifically used to process files read objects

Writer the---------outputstream-------------FileWriter: A character stream specifically used to process files write objects


Common methods in Reader:

1. Int read (): Reads a character, returns which character is read, and returns-1 if it is read to the end of the stream.

2.int read (char[]): Stores the read characters into the specified array, returning the number of characters read, that is, the number of elements loaded into the array, or 1 if the end of the stream is read.

3.close (): Read characters It is useful for Windows system function, which is to release resources after use.


Common methods in Writer:

1.writer (CH): writes a character to the stream.

2.writer (char[]): Writes an array of characters to the stream.

3.writer (String): Writes a string to the stream.

4.flush (): Flushes the stream, flushes the data in the stream to the destination, and the stream still exists.

5.close (): Closes the resource, calls Flush () before shutting down, refreshes the data in the stream to the destination, and then closes the stream.


FileWriter: This class does not have a specific method, only its own constructor.

This class is characterized by:

1. For working with text files

2. There is a default encoding table in this class

3. There is a temporary buffer in the class

Constructor: When writing a Stream object initialization, you must have a destination to store the data, FileWriter (String filename)

What does the constructor do again?

1. Invoke system resources

2. Create the file in the specified location (overwrite the file if it already exists)

FileWriter (String filename,boolean Append): This constructor: When the passed-in boolean argument is true, the data is continued at the end of the specified file.

FileReader:

1. Stream objects for reading text files

2. For associating text files

Constructor: When reading a Stream object initialization, you must specify a read file. If the file does not exist, FileNotFoundException will occur.

FileReader (String filename)

Demo1:

Package learn1; Import Java.io.FileWriter;
Import java.io.IOException; /**
* Complete exception handling mechanism
* @author JT
*
*/
public class Demo2 {
public static void Main (string[] args) {
FileWriter FW = NULL;
try {
FW = new FileWriter ("D:\\demo2.txt");
Fw.write ("ABCDA");
Fw.flush ();
Fw.write ("KKKK");
catch (IOException e) {
System.out.println (E.tostring ());
}finally{
if (fw!=null) {
try {
Fw.close ();
catch (IOException e) {
System.out.println ("Close:" +e.tostring ());
}
}
}
}
}

For a constructor that reads or writes a stream object, as well as a read-write method, and a refresh-shutdown method throws IOException or its subclasses, it is handled throws or Try,catch

Complete exception Handling method:

Import Java.io.FileWriter;
Import java.io.IOException; /**
* Complete exception handling mechanism
* @author JT
*
*/
public class Demo2 {
public static void Main (string[] args) {
FileWriter FW = NULL;
try {
FW = new FileWriter ("D:\\demo2.txt");
Fw.write ("ABCDA");
Fw.flush ();
Fw.write ("KKKK");
catch (IOException e) {
System.out.println (E.tostring ());
}finally{
if (fw!=null) {
try {
Fw.close ();
catch (IOException e) {
System.out.println ("Close:" +e.tostring ());
}
}
}
}
}


Another detail:

When you specify an absolute path, there are two ways to define a directory delimiter, 1. Backslash: \ must write two new FileWriter ("D:\\demo1.txt") 2. Slash/write only one can be new FileWriter ("D:/demo2.txt")


Read an existing text file, print the text file, read one character at a time to print out, the efficiency is not high.

Package learn1;

Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException;

/**
* Read an existing text file
* read one character at a time and print it out
* @author JT
*
*/
public class Demo3 {
public static void Main (string[] args) throws IOException {
FileReader FR = new FileReader ("D:/demo.txt");
int ch=0;
Read one character at a time
while (ch = fr.read ())!=-1) {
System.out.println ((char) ch);
}
Fr.close ();

}
}


Read a character to a character array, read the 1KB after printing out

Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException; /**
* Read a character in a character array, read 1KB in print
* @author JT
*
*/
public class Demo4 {
public static void Main (string[] args) {
FileReader FR = null;
try {
FR = new FileReader ("D:/demo.txt");
char[] buf = new char[1024];//The length is usually 1024 integer times
int len=0;
while ((Len=fr.read (BUF))!=-1) {
System.out.println (New String (Buf,0,len));
}
catch (IOException e) {
System.out.println (E.tostring ());
}finally{
if (Fr!=null) {
try {
Fr.close ();
catch (IOException e) {
System.out.println ("Close:" +e.tostring ());
}
}
}
}
}


The buffer of the character stream: the appearance of the buffer increases the operation efficiency of the convection, and the principle is to encapsulate the array.

The corresponding object:

BufferedWriter: Unique Method: NewLine (): cross-platform line breaks

BufferedReader: Unique method: ReadLine (): Once a row is read, the character data before the row tag is returned as a string when the row is marked, and null is returned when the end is read.

When using a buffer object, it is clear that the buffer exists to enhance the functionality of the stream, so when the buffer object is created, a stream object exists. In fact, the buffer is in the use of the Flow object method, but added to the array of data to the temporary cache. In order to improve the efficiency of operational data.












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.