In the previous chapter, we introduced the knowledge of set framework in detail , In the next few articles we'll talk about Java The other and most important knowledge in the book ——IO flow , This article is mainly about IO Some basic concepts of stream and related applications of character stream .

IO flow

Introduce IO Let's first introduce what is IO,IO yes input、output For short , So the so-called IO A stream is an input-output stream , Understanding this will greatly promote the learning in the future .

Flow direction classification

Just as dry batteries have positive and negative electrodes , There is also a difference in the direction of flow , Our common classification is based on the flow direction , " flow " The stream to the current program becomes the input stream, that is I One end ," flow " The output stream of the current program becomes the output stream O One end , With this concept , We will IO Streams are divided into input stream and output stream .

Base class of stream

We divide the flow into two schools according to different operation objects , One group operates on character data, which we call character stream , The school of manipulating bytes is what we call byte streams . The architecture is as follows :

Character stream :Reader、Writer

Byte stream :InputStream、OutputStream

Byte stream : Stream object processing byte data . The data we know about devices, whether it's pictures or videos , written words , They are all stored in binary . Binary systems end up with a 8 Bit represents data unit , So the smallest unit of data in a computer is bytes . in other words , Byte stream can process all data on the device , So byte stream can process character data as well .

Character stream : The encoding of data stored on the computer of Chinese platform is GBK, The national standard is unicode So in the process of mutual transformation, there will be garbled code , Therefore, it is necessary to specify the encoding table while obtaining the Chinese byte data to correctly parse the data . For ease of operation , So encapsulate the byte stream and encoding as objects , This object is a character stream .

It is important to note that , The above four categories and two schools have one basic characteristic , The subclass ends with the name of the parent class , This is a great convenience for us to master , such as InputStream Subclasses of FileInputStream;Writer Subclasses of FileWriter.

Character stream

Abstract base class :

|--Reader: Character input stream

|--Writer: Character output stream

FileWriter

FileWriter yes Writer A subclass of ( And it's OutputStreamWriter Subclasses of ), Convenient subclass for writing character files

Construction method :

|--FileWriter(File file)

According to the given File Object constructs a FileWriter object .

|--FileWriter(File file, boolean append)

According to the given File Object constructs a FileWriter object .

|--FileWriter(FileDescriptor fd)

Construct... Associated with a file descriptor FileWriter object .

|--FileWriter(String fileName)

Construct a... Based on the given filename FileWriter object .

|--FileWriter(String fileName, boolean append)

Based on the given file name and indicating whether to append the boolean Value to construct FileWriter object .

It can realize the appending and writing of files , The second parameter indicates whether to append the write , The default is false, It will start writing again , If it is true, Will append the write

Common methods

|--void write(String str): Write string .

|--abstract void flush(): Refresh the buffer of the stream

|--abstract void close(): Close this stream , But refresh it first .

Application demonstration

    1、FileWriter Use case of

New file , And write characters in the file

import java.io.FileWriter;

import java.io.IOException;

public class Demo2 {

public static void main(String[] args) throws IOException {

// Create a flow object , Create data storage files , Specify the directory and file name

FileWriter f=new FileWriter("E:/aa.txt");

// call FilterWriter Of writer(String s) Method , Output the specified character to the new file

f.write(" I am a FileWriter Created files ");

// Refresh the data in the character stream , If you don't refresh and close the stream object, there will be an empty file

f.flush();

// Close flow object , Recycle stream resources , After closing the stream object, the stream object cannot be used , This is related to flush There's a big difference

f.close();

}

}

    2、 Add characters to the end of an existing file , In fact, only one change is needed

FileWriter f=new FileWriter("E:/aa.txt",true);

Other parts are the same

FileReader

FileReader yes Reader A subclass of ( yes InputStreamReader The direct subclass of ), Convenience class for reading character files

Construction method :

|--FileReader(File file)

Reading data from given File Create a new FileReader.

|--FileReader(FileDescriptor fd)

Reading data from given FileDescriptor Create a new FileReader.

|--FileReader(String fileName)

Create a new... Given the filename from which to read the data FileReader.

Two reading methods :

|--int read(): Read a single character .

|--int read(char[] cbuf): Read characters into an array .

Application demonstration

1、 read()

import java.io.FileReader;

import java.io.IOException;

public class Demo2 {

public static void main(String[] args) throws IOException {

// The first way read();

FileReader fr = new FileReader("E:/aa.txt");

// Create a file read stream object , Associated with a file of the specified name .

// Make sure that the file already exists , If it doesn't exist , Exceptions will occur FileNotFoundException

int ch = 0;

while((ch = fr.read())!=-1){

System.out.print((char)ch);

}

fr.close();

}

}

The second way read(char[])

import java.io.FileReader;

import java.io.IOException;

public class Demo2 {

public static void main(String[] args) throws IOException {

// The second way read(char[]);

FileReader fr = new FileReader("E:/aa.txt");

int i = 0;

char[] ch2 = new char[1024];

while((i = fr.read(ch2))!=-1){

System.out.print(new String(ch2,0,i));

}

fr.close();

}

}

The base class is introduced above Writer as well as Reader The basic usage of , Whether it's Writer still Reader One drawback of the above usage is that it is inefficient , In order to improve efficiency, we need to learn the following —— Character stream buffer

Character stream buffer

The appearance of character stream buffer is to improve the efficiency of reading and writing data , Enhanced functionality based on Streaming , Here's a design pattern —— Decoration design mode , About the common design patterns, there will be a special topic to introduce in the following article, and I will not explain it in detail here .

Common buffer classes

BufferedWriter(? Extends Writer)

BufferedReader(? Extends Reader)

BufferedWriter

Write text to character output stream , Buffer individual characters , To provide a single character 、 Efficient writing of arrays and strings . This buffer provides a cross platform newline :newLine();

This method ( All method return types void):

|--close(): Close this stream , But refresh it first .

|--flush(): Refresh the buffer of the stream .

|--newLine(): Write a line separator . Cross platform use

|--write(char[] cbuf, int off, int len): Write a part of the character array .

|--write(int c): Write a single character .

|--write(String s, int off, int len): Write a part of the string .

Use demonstration

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

public class Demo2 {

public static void main(String[] args) throws IOException {

// Create a character write stream object .

FileWriter fw = new FileWriter("E:/aa.txt");

// In order to improve the efficiency of character writing stream . Added buffer technology .

// Just pass the stream object that needs to be improved as a parameter to the constructor of the buffer .

BufferedWriter bufw = new BufferedWriter(fw);

for(int x=1; x<5; x++){

bufw.write(" The first "+x+" Time to write ");

bufw.newLine();

bufw.flush();// Just use the buffer , Just remember to refresh .

}

// Actually, close the buffer , Is to close the stream object in the buffer .

bufw.close();

}

}

BufferedReader

Read text from character input stream , Buffer individual characters , So as to realize the character 、 Efficient reading of arrays and rows .

This buffer provides a way to read one line at a time readLine(), It is convenient for obtaining text data . When to return to null when , Read to the end of the file .( notes :readLine Method returns only the data content before the carriage return character . Does not return carriage return .)

Common methods :

|--void close(): Close the stream and release all resources associated with it .

|--int read(): Read a single character .

|--int read(char[] cbuf, int off, int len): Reading characters into a part of an array .

|--String readLine(): Read a line of text .

Examples of use

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class Demo2 {

public static void main(String[] args) throws IOException {

// Create a read stream object associated with the file .

FileReader fr = new FileReader("E:/aa.txt");

// In order to improve efficiency . Add buffer technology . Pass the character read stream object as a parameter to the constructor of the buffer object .

BufferedReader bufr = new BufferedReader(fr);

String line = null;// Define a variable to temporarily store data

while((line=bufr.readLine())!=null)// The return value is not null It's been circulating

{

System.out.print(line);

}

bufr.close();

}

}

eighteen 、Java Basics --------IO Stream system and character stream

  1. twenty 、Java Basics --------IO Other objects of flow

    In the above two articles, we introduced IO This paper introduces byte stream and character stream in detail , This article is mainly about the operation of the file File. Transformation flow . Standard input and output .Properties. Print stream and sequence stream . File File English is " file ...

  2. Java Learn from scratch (JAVA IO- Redirect IO)

    One . Three static variables java.lang.System Three static variables are provided System.in( Default keyboard ) System.out( The default display ) System.err Two . Override the method System It provides three important ...

  3. Java Basics IO Class byte array stream

    package IODemo; // Byte array stream : The internal maintenance of this is an array of bytes , We can use the read mechanism of the stream to handle strings No need to close , Not to report IO abnormal // ByteArrayInputstream ByteAr ...

  4. java Basics -IO Flow object of Properties aggregate

    java Basics -IO Flow object of Properties aggregate author : Yin Zhengjie Copyright notice : Original works , Declined reprint ! Otherwise, the legal liability will be investigated . One .Properties Set characteristics Properties Class represents a set of persistent properties . ...

  5. Java Basics -IO Character class of stream object (FileWrite And FileReader)

    Java Basics -IO Character class of stream object (FileWrite And FileReader) author : Yin Zhengjie Copyright notice : Original works , Declined reprint ! Otherwise, the legal liability will be investigated . One . Introduction to common coding 1>ASCII We know that computers are ...

  6. Java Basic learning summary (13)—— flow IO

    One .JAVA Streaming input / The output principle Streams are used to read and write data ,java There is a class called File, It encapsulates the file name of the file , It's just an object in memory , The real file is a piece of space on the hard disk , All kinds of data are stored in this file , We ...

  7. java Basics IO Flow synthesis plus exercises

    IO Stream beginners are a little confused in their study , Today we will talk about IO flow , I hope the explanation can help you IO Streams are divided into byte streams , Character stream , Buffer flow . We just need to remember these three . 1* The byte stream has : Byte input stream (FileInputStrea ...

  8. Java Basics ---IO( One )---IO Flow overview 、 Character stream 、 Byte stream 、 Flow operation law

    Lesson one      IO summary summary 1.IO flow : namely InputOutput Abbreviation . 2. characteristic : 1)IO Streams are used to handle data transfer between devices . 2)Java The operation of data is by means of flow . 3)Java The objects used to manipulate the flow are ...

  9. Java Basics IO flow ( Two ) Byte stream case

    JAVA Basics IO flow ( One )https://www.cnblogs.com/deepSleeping/p/9693601.html ① Read the contents of the specified file , according to 16 Output to the console among ,Integer.to ...

Random recommendation

  1. python use Tesseract Read the Chinese in the picture , Garbled

    To http://download.csdn.net/detail/wanghui2008123/7621567 Download Chinese Simplified package And then find tessdata Catalog , hold eng.traineddata Replace with chi ...

  2. sh Script learning : sh Script 、sed、awk

    sh Script sh Command batch file , Support more complex logic . Shell The variables in the Parameters $0 Current script path $1....$n The script executes the corresponding second n Parameters conditional File to judge test [op] path e There is ...

  3. NOI 2005 Maintenance series

    Mom, I finally passed !!! It's the data pit !!! Abandon treatment abandon treatment abandon treatment abandon treatment !!!! I've been adjusting it all day .... By GET_SUM 8 0 Beat .... Don't say anything .... Or I'm too young .... Update the constant , It's OK to run : ...

  4. CentOS uninstall openoffice

    rpm -e `rpm -qa |grep openoffice` `rpm -qa |grep ooobasis` This is quite thorough

  5. SAP problem 【 Reprint 】

    1.A: Error in company code allocation depreciation table ? Error in company code allocation depreciation table , The tip is "3000 The company code entry of is incomplete - See long text " I hope you can help me to have a look . 3000 The company code entry of is incomplete - See ...

  6. linux- File data manipulation awk command

    The last column is : Interactive shell The contents in single quotation marks will not be bash Expand cut You can do the same "\t" tabs cut and sed The combination can also achieve Expand : Anonymous methods can have multiple ,and There can only be one method ...

  7. Linux The mapping between virtual address and physical address

    * background In general ,Linux In the system , Process 4GB The memory space is divided into two parts ------ User space and kernel space , The sizes are 0~3G,3~4G. User processes usually , Only virtual addresses in user space can be accessed , Can't access the kernel ...

  8. Web standard : Four 、 Vertical navigation menu and secondary pop-up menu

    Web standard : Four . Vertical navigation menu and secondary pop-up menu Knowledge point : 1. Vertical list 2. The default style of the label 3.css descendent selector 4.css Grouping of selectors 5. Vertical secondary list 6. Relative positioning and absolute positioning   1) Vertical list You can see ...

  9. Maven Under the project java.lang.ClassNotFoundException Conventional solutions

    There are a lot of changes to be made online .class .project Sometimes it doesn't work . The following method is suitable for the project and has been referenced jar, But the runtime ClassNotFound, Please try the following method : serious : Error con ...

  10. logstash Middle configuration GeoIP Analyzing geographic information

    logstash Configured in GeoIP Database analysis of ip 了 , Here is open source ip data source , Used to analyze the client's ip Place of ownership . The official website is here :MAXMIND download GeoLiteCity database wget http://ge ...