IO stream [conversion stream, character output stream, data stream, object stream] (3) - comprehensive detailed explanation (learning summary --- from entry to deepening)

Table of contents

conversion stream

character output stream

data flow

 object flow


conversion stream

InputStreamReader/OutputStreamWriter用来实现将字节流转化
成字符流。

Solve garbled characters by converting streams

ANSI (American National Standards Institute) American National Standards Institute

public class TestInputStreamReader {
    public static void main(String[] args) {
        //创建文件字节输入流对象
        try(FileInputStream fis = new FileInputStream("d:/sxt.txt");
            //创建转换流(字节到字符的转换)流对象,并在该对象中指定编码。
            InputStreamReader isr = new InputStreamReader(fis,"gbk")){
            StringBuilder sb = new StringBuilder();
            //操作流对象
            int temp = 0;
            while((temp = isr.read()) != -1)
           {
                sb.append((char) temp);
           }
            System.out.println(sb);
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Realize keyboard input and screen output by converting stream

import java.io.*;
public class TestConvertStream {
    public static void main(String[] args) {
    // 创建字符输入和输出流:使用转换流将字节流转换成字符流
    BufferedReader br = null;
    BufferedWriter bw = null;
 try {
      br = new BufferedReader(new InputStreamReader(System.in));
      bw = new BufferedWriter(new OutputStreamWriter(System.out));
      // 使用字符输入和输出流
     String str = br.readLine();
     // 一直读取,直到用户输入了exit为止
     while (!"exit".equals(str)) {
     // 写到控制台
    bw.write(str);
    bw.newLine();// 写一行后换行
    bw.flush();// 手动刷新
    // 再读一行
    str = br.readLine();
   }
 } catch (IOException e) {
     e.printStackTrace();
 } finally {
 // 关闭字符输入和输出流
 if (br != null) {
    try {
         br.close();
       } catch (IOException e) {
      e.printStackTrace();
     }
 }
 if (bw != null) {
 try {
      bw.close();
     } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

Read a text file via a byte stream and add line numbers

public class TestLineNumber2 {
    public static void main(String[] args) {
   //创建字符输入缓冲流、输入字节到字符转换流、文件字节输入流对象
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream("d:/sxt.txt")));
            //创建字符输出缓冲流、输出字符到字节转换流、文件字节输出流对象
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream("d:/sxt4.txt")))){
            //操作流
            String temp = "";
            //序号变量
            int i = 1;
            //按照行读取
            while((temp = br.readLine()) != null){
                bw.write(i+","+temp);
                //换行
                bw.newLine();
                //序号累加
                i++;
           }
            //刷新
            bw.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Realize keyboard input and screen output by converting stream

System.in is a byte stream object representing keyboard input.

System.out is a byte stream object representing output to the screen.

public class TestKeyboardInput {
    public static void main(String[] args) {
           //创建键盘输入相关流对象
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
           //创建向屏幕输出相关流对象
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))){
            while(true){
                bw.write("请输入:");
                bw.flush();
                //获取键盘输入的字符串
                String input = br.readLine();
                //判断输入的内容是否含有退出关键字。
                if("exit".equals(input) || "quit".equals(input)){
                    bw.write("Bye Bye !");
                    bw.flush();
                    break;
               }
            //将读取到键盘输入的字符串,输出到屏幕。
                bw.write("您输入的是:"+input);
                bw.newLine();
                bw.flush();
           }
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

character output stream

 The stream object PrintWriter for character output is specially provided in Java's IO stream. This object has an automatic line refresh buffer character output stream, which is characterized by the ability to write out character strings by line, and can implement automatic line wrapping through the println(); method.

public class TestPrintWriter {
   public static void main(String[] args) {
         //创建字符输出流对象
        try(PrintWriter pw = new PrintWriter("d:/sxt5.txt")){
            //调用不带换行方法完成内容的输出
            pw.print("abc");
            pw.print("def");
            //调用带有自动换行方法完成内容的输出
            pw.println("Oldlu");
            pw.println("sxt");
            pw.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Add line numbers through a character output stream

public class TestLineNumber3 {
    public static void main(String[] args) {
        //创建字符输入缓冲流对象与文件字符输入流对象
        try(BufferedReader br = new BufferedReader(new FileReader("d:/sxt.txt"));
            //创建字符输出流对象
            PrintWriter pw = new PrintWriter("d:/sxt6.txt")){
            //操作流
            String temp = "";
            //定义序号变量
            int i = 1;
            while((temp = br.readLine()) != null){
                pw.println(i+","+temp);
                //序号累加
                i++;
           }
            //刷新
            pw.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

data flow

 Data streams use "basic data types and string types" as data sources, allowing programs to manipulate Java basic data types and string types from the underlying input and output streams in a machine-independent manner. DataInputStream and DataOutputStream provide methods that can access all machine-independent Java basic types of data (such as: int, double, String, etc.).

public class TestDataStream {
    public static void main(String[] args) {
        //创建数据输出流对象与文件字节输出流对象
        try(DataOutputStream dos = new DataOutputStream(new FileOutputStream("d:/data"));
           //创建数据输入流对象与文件字节输入流对象
           DataInputStream dis = new DataInputStream(new FileInputStream("d:/data"))){
            //将如下数据写入到文件中
            dos.writeChar('a');
            dos.writeInt(10);
            dos.writeDouble(Math.random());
            dos.writeBoolean(true);
            dos.writeUTF("山东聊城");
            //手动刷新缓冲区:将流中数据写入到文件中
            dos.flush();
            //直接读取数据:读取的顺序要与写入的顺序一致,否则不能正确读取数据。
            System.out.println("char: " + dis.readChar());
            System.out.println("int: " + dis.readInt());
            System.out.println("double: " + dis.readDouble());
            System.out.println("boolean: " + dis.readBoolean());
            System.out.println("String: " + dis.readUTF());
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Oldlu Tip: When using data streams, the order of reading must be consistent with the order of writing, otherwise the data cannot be read correctly.

 object flow

 The data stream we learned earlier can only read and write basic data types and string types, and cannot read objects (except strings). If we want to read and write an object, we need to learn a pair of new The processing stream of: ObjectInputStream/ObjectOutputStream.

 Handle basic data type data

ObjectInputStream/ObjectOutputStream handle primitive data types.

public class TestObjectStreamBasicType {
    public static void main(String[] args) {
            //创建对象输出流对象与文件字节输出流对象
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:/data2"));
           //创建对象输入流对象与文件字节输入流对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/data2"))){
            //将如下数据写入到文件中
            oos.writeInt(10);
            oos.writeDouble(Math.random());
            oos.writeChar('a');
            oos.writeBoolean(true);
            oos.writeUTF("你好,山东聊城");
            oos.flush();
            //必须要按照写入的顺序读取数据
            System.out.println("int: "+ois.readInt());
            System.out.println("double: "+ois.readDouble());
            System.out.println("char: "+ois.readChar());
            System.out.println("boolean: "+ois.readBoolean());
            System.out.println("String: "+ois.readUTF());
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Notice

1. The object stream can not only read and write objects, but also read and write basic data types.

2. When reading and writing basic data types, the order of reading must be consistent with the order of writing, otherwise the data cannot be read correctly.

review:

 Introduction to IO stream technology

 What is IO

Input (Input) refers to: the program can obtain data from an external system (the core meaning is "read", read external data). Output (Output) refers to: the program outputs data to the external system so that the external system can be operated (the core meaning is "write", write the data to the external system). The java.io package provides us with related APIs to implement input and output operations on all external systems. This is the technology we will learn in this chapter.

 What is a data source

Data source data source, which provides the original medium of data. Common data sources include: databases, files, other programs, memory, network connections, and IO devices. as the picture shows.

 

 The data source is divided into: source device and target device.

1 Source device: Provide data for the program, generally corresponding to the input stream.

2 Target device: The destination of the program data, generally corresponding to the output stream.

 flow concept

Stream is an abstract and dynamic concept, which is a series of continuous and dynamic data collections. For the input stream, the data source is like a water tank, the stream is like the water flowing in the water pipe, and the program is our final user. We transmit the data (information) in the data source (Source) to the program (Program) through the stream (A Stream). For the output stream, the target data source is the destination (dest), and we transfer the data (information) in the program (Program) to the destination data source (dest) through the stream (A Stream).

 Relationships between streams and source and target data sources:

 

 Oldlu Tips

The division of input/output streams is relative to the program, not relative to the data source.

The first simple IO stream program 

 When the program needs to read the data of the data source, it will open a stream to the data source through the IO stream object, and the data in the data source can be read sequentially through the related methods of the IO stream object.

Use stream to read file content (non-standard writing, only for testing)

import java.io.*;
public class TestI01 {
 public static void main(String[] args) {
 try {
 //创建输入流
 FileInputStream fis = new FileInputStream("d:/a.txt"); // 文件内容是:abc
 //一个字节一个字节的读取数据
 int s1 = fis.read(); // 打印输入字符a对应的ascii码值97
 int s2 = fis.read(); // 打印输入字符b对应的ascii码值98
 int s3 = fis.read(); // 打印输入字符c 对应的ascii码值99
 int s4 = fis.read(); // 由于文件内容已经读取完毕,返回-1
 System.out.println(s1);
 System.out.println(s2);
 System.out.println(s3);
 System.out.println(s4);
 // 流对象使用完,必须关闭!不然,总占用系统资源,最终会造成系统崩溃!
   fis.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
  }
}

In the above case, we should pay attention to the following points:

1. The content of the file we read is known, so we can use a fixed number of "int s= fis.read();" statements to read the content, but in actual development, we usually don't know the content of the file at all, so We need to use while loop when reading.

2. In order to ensure the normal closing of the stream after an exception occurs, usually the closing statement of the stream should be placed in the finally statement block, and it is necessary to judge whether the stream is null.

 The classic way of writing IO stream

 

 Use stream to read file content (classic code, must master)

import java.io.*;
public class Test2 {
 public static void main(String[] args) {
 FileInputStream fis = null;
 try {
       fis = new FileInputStream("d:/a.txt"); // 内容是:abc
       StringBuilder sb = new StringBuilder();
       int temp = 0;
      //当temp等于-1时,表示已经到了文件结尾,停止读取
      while ((temp = fis.read()) !=-1) {
         sb.append((char) temp);
     }
         System.out.println(sb);
 } catch (Exception e) {
         e.printStackTrace();
 } finally {
 try {
 //这种写法,保证了即使遇到异常情况,也会关闭流对象。
 if (fis != null) {
      fis.close();
     }
  } catch (IOException e) {
      e.printStackTrace();
    }
   }
 }
}

 IO Stream New Grammar Classic Writing

 In JDK7 and later versions, you can use the try-with-resource syntax to close resources more gracefully. java.lang.AutoCloseable interface: The java.lang.AutoCloseable interface contains a close method, which is used to close resources. As long as the object implements the java.lang.AutoCloseable interface, you can use try-with-resource to close the resource. Use the latest try-with-resource simplification (classic code, must master)

public class Test3 {
    public static void main(String[] args) {
        //使用try-with-resource方式关闭资源。
        //在try中打开资源,不需要在代码中添加finally块关闭资源。
        try(FileInputStream fis = new FileInputStream("d:/a.txt");){
            StringBuilder sb = new StringBuilder();
            int temp=0;
            while((temp = fis.read()) != -1)
           {
                sb.append((char) temp);
           }
            System.out.println(sb);
       }catch(Exception e){
            e.printStackTrace();
       }
   }

Oldlu suggested that the above code is a very typical IO stream code, and the use of other stream objects is basically the same pattern!

 

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131647418