On the IO stream of Java learning (character stream, byte stream)

 

IO style

1. IO stream: used to process data on the device.

Equipment: hard disk, memory, keyboard entry.

2. IO has specific categories:

(1) Depending on the type of data processed: byte stream and character stream.

(2) According to different flow directions: input flow and output flow.

Origin of character stream:

Because of different file encodings, there are character stream objects that operate efficiently on characters.

Principle: In fact, when reading bytes based on the byte stream, check the specified code table.

The difference between byte stream and character stream:

(1) When a byte stream is read, a byte is returned when a byte is read.

When the character stream uses the byte stream to read one or more bytes (the number of bytes corresponding to Chinese is two, and it is 3 bytes in the UTF-8 code table), first check the specified encoding table, and set the The found characters are returned.

(2) Byte stream can handle all types of data, such as MP3, picture, avi. The character stream can only handle character data.

Conclusion: As long as it is dealing with plain text data, it is necessary to give priority to using the character stream, and otherwise use the byte stream.

 

 

The IO system has two basic functions: read and write.

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

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

 

1. Character stream:

Reader  

|--InputStreamReader  

   |--FileReader: A character read stream object specially used to process files.  

Writer

 |--OutputStreamWriter  

   |--FileWriter: Character write stream object specially used to process files

 

 

Common methods in Reader:  

1. int read():  

   Read a character. What is returned is the character that was read. Returns -1 if the end of the stream is read.  

2. int read(char[]):    

  Store the read characters in the specified array, and return the number of characters read, that is, the number of elements loaded into the array. Returns -1 if the end of the stream is read.  

3. close():    

  Reading characters actually uses the function of the window system, and it is hoped that the resources will be released after use.

 

 

Common methods in Writer:  

1, write(ch): Write a character to the stream.  

2, write(char[]): Write a character array to the stream.

3, write(String): Write a string to the stream.  

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

5. close(): close the resource: flush() will be called before closing to refresh the data in the stream to the destination. The stream is closed.

 

FileWriter:  

This class has no specific methods. Only its own constructor.  

This type of feature is that,  

1, for processing text files.  

2. There is a default coding table in this class,  

3. There is a temporary buffer in this class.

     

Constructor: When writing to a stream object initialization, there must be a destination for storing data.

  FileWriter(String filename): What does this constructor do?  

1. Call system resources.  

2. Create a file in the specified location.  

 Note: If the file already exists, it will be overwritten.  

FileWriter(String filename,boolean append):  

   This constructor: When the value of the boolean type passed in is true, the data will be continued at the end of the specified file.

 

FileReader:  

1, a stream object for reading text files.  

2, used to associate text files.

 

 Constructor: When initializing the read stream object, you must specify a file to be read.    

FileNotFoundException occurs if the file does not exist.  

FileReader(String filename);

 

Constructors that read or write stream objects, as well as read and write methods, and flush close functions throw IOException or its subclasses.

So it has to be processed, or throws is thrown, or try and catch are processed.

 

Store text data to a file:

copy code
 1 import java.io.*;
 2 public class TestFileWriter1 {
 3     public static void main(String[] args){
 4         FileWriter fw=null;
 5         try{
 6             fw=new FileWriter("D:\\JAVA练习代码\\123.txt");
 7             fw.write("abcdec");
 8             fw.flush();
 9             fw.write("kkkk");
10         }catch(IOException e){
11             System.out.println(e.toString());
12         }
13         finally{
14             if(fw!=null)
15                 try{
16                     fw.close();
17                 }catch (IOException e) {
18                     System.out.println("close"+e.toString());
19                 }
20         }
21     }
22 }
copy code

 

 

Another small detail:  

When specifying absolute paths, there are two ways to define directory separators:

1, backslashes but be sure to write two. \\ new FileWriter("c:\\demo.txt");

2. Just write a slash /. new FileWriter("c:/demo.txt");

 

Read a character and store it in the character array, and print it after reading 1Kb.

copy code
1  import java.io.*;
 2  public  class TestFileReader1 {
 3      public  static  void main(String[] args){
 4          FileReader fr= null ;
 5          try {
 6              fr= new FileReader("D:\\JAVA practice code\\ abc.txt");
 7              char []buf= new  char [1024];     // The length is usually an integer multiple of 1024 
8              int len=0;
 9              while ((len=fr.read(buf))!= -1){
 10                  System.out.println( new String(buf,0,len));
11             }
12         }catch(IOException e){
13             System.out.println(e);
14         }
15         finally{
16             if(fr!=null){
17                 try{
18                     fr.close();
19                 }catch(IOException e){
20                     System.out.println("close"+e);
21                 }
22             }
23         }
24     }
25}
copy code

 

 

 

 

Buffer of character stream:

 

The emergence of buffers improves the efficiency of operations on streams.

Principle: In fact, it is to encapsulate the array.

The corresponding object:

BufferedWriter:

  Unique method:

    newLine(): Cross-platform newline.

BufferedReader:

  Unique method:

    readLine(): Reads one line at a time, and returns the character data before the line mark as a string when the line mark is reached. When the end is read, null is returned.

 

When using a buffer object, it should be clear that the existence of the buffer is to enhance the function of the stream, so when the buffer object is resumed, the existing stream object must exist.

In fact, the internal buffer is using the method of stream object, but adding an array to temporarily store the data, in order to improve the efficiency of operating the data.

 

Reflection on the code:

Write buffer object:

//To create a buffer object, you must pass the stream object as a parameter to the buffer's constructor.

BufferedWriter bw=new BufferedWriter(new FileWriter(“abc.txt”));

bw.write("abce"); //Write the data to the buffer.

bw.flush();//Refresh the data in the buffer. Flush the data to the destination.

bw.close();//Close the buffer, in fact, close the stream object that is wrapped inside.

Read buffer object:

BufferedReader br=new BufferedReader(new FileReader("abc.txt"));

String s=null;

 

copy code
 1 import java.io.*;
 2 public class TestBufferStream {
 3     public static void main(String[] args){
 4         try{
 5             BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Java练习代码\\abc.txt"));
 6             BufferedReader br=new BufferedReader(new FileReader("D:\\Java练习代码\\abc.txt"));
 7             String s=null;
 8             for(int i=1;i<=100;i++){
 9                 s=String.valueOf(Math.random());
10                 bw.write(s);
11                 bw.newLine();
12             }
13             bw.flush();
14             while((s=br.readLine())!=null){
15                 System.out.println(s);
16             }
17             bw.close();
18             br.close();
19         }catch (IOException e){
20             e.printStackTrace();
21         }    
22     }
23 }
copy code

 

 2. Byte stream:

Abstract base classes: InputStream, OutputStream.

Byte streams can operate on any data.

Note: The array used by the character stream is a character array, char[] chs;

   The array used by the byte stream is a byte array, byte[] bt;

FileOutputStream fos=new FileOutputStream(“a.txt”);

fos.write("abcde"); //Write the data directly to the destination.

fos.close();//Only close the resource.

FileInputSteam fls=new FileInputStream("a.txt");

//fis.available();//Get the associated file bytes. If the file size is not large, you can do this.

byte[]buf=new byte[fis.available()];//Create a just-right buffer. //But this has a disadvantage, that is, when the file is too large and the size exceeds the content space of the JVM, the memory will overflow.

fis.read(buf);

System.out.println(new String(buf));

 

example:

  Requirements: copy a picture.

BufferedInputStream bufis=new BufferedInputStream(new FileInputStream("1.jpg"));

BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("2.jpg"));

int by=0;

while(by=bufis.read()!=-1){

  bufos.write(by);

  bufos.newLine();

}

bufis.close();

bufos.close();

 

summary:

Stream objects currently learned:

字符流: FileReader  FileWriter  BuffereedReader  BufferedWriter

字节流:FileInputStream  FileOutputStream   BufferedInputStream  BufferedOutputStream

 

Replenish:

1. The read() method of the byte stream reads a byte. Why not return byte type, but int type?

Because the read method returns -1 when it reads the end, and it is easy to have multiple 1s in a row in the manipulated data, and reading 8 1s in a row is -1, which will cause the reading to stop early. So the read byte is promoted to an int type value, but only the original byte is kept, and the remaining binary bits are filled with 0.

The specific operation is: byte&255 or byte&0xff

2. For the write method, one byte can be written at a time, but an int type value is received. Only the lowest byte (8 bits) of this int value is written.

Simply put: the read method improves the read data, and the write method converts the operated data.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324809433&siteId=291194637