This is the 13th day of my participation in the August More Text Challenge.More challenges in August

Reader and Writer

The character input stream Reader

  • Reader(): Creates a new character stream reader whose key parts will be synchronized on the reader itself
  • read(): Reads a character
  • read(char[] cbuf): reads characters into an array
  • read(char[] cbuf, int off, int len): reads characters into part of an array

Character output stream Writer

  • Writer(): Creates a new character stream writer whose key parts will be synchronized on the writer itself
  • append(char c): appends the specified character to the writer
  • append(CharSequence csq): appends the specified character sequence to the writer
  • append(CharSequence csq, int start, int end): appends the subsequence of the specified character sequence to the writer
  • write(char[] cbuf): Writes an array of characters
  • write(String str): Writes a string
  • write(String str, int off, int len): Writes part of a string
  • flush(): refresh the flow

InputStreamReader, OutputStreamWriter

InputStreamReader and OutputStreamWriter can convert a byte stream to a character stream and specify a character encoding

try {
    InputStreamReader fileReader = new InputStreamReader(new FileInputStream("D:/ test cases.txt"));
    OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream("D:/ Test cases-12.txt"), StandardCharsets.UTF_8);
    int data;
    while((data = fileReader.read()) ! = -1) {
        System.out.print((char) data);
        fileWriter.write((char) data);
    }
    fileWriter.close();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

FileReader, FileWriter

File character streams FileReader and FileWriter

Note that only the default character encoding can be used for FileReader and FileWriter

FileReader:

try {
    FileReader fileReader = new FileReader("D:/ test cases.txt");
    int data;
    while((data = fileReader.read()) ! = -1) {
        System.out.print((char) data); }}catch (IOException e) {
    e.printStackTrace();
}
Copy the code

FileWriter Input example:

try {
    FileWriter fileWriter = new FileWriter("D:/ test cases.txt".true);
    fileWriter.write("Append string");
    fileWriter.flush();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

The character stream of FileReader and FileWriter files is used to copy files

try {
    FileReader fileReader = new FileReader("D:/ test cases.txt");
    FileWriter fileWriter = new FileWriter("D:/ Test cases-12.txt".true);
    int data;
    while((data = fileReader.read()) ! = -1) {
        System.out.print((char) data);
        fileWriter.write((char) data);
    }
    fileWriter.close();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

CharArrayReader, CharArrayWriter

CharArrayReader and CharArrayWriter are similar to byte array bytes except that the unit is a char character and the character encoding can be specified

try {
    InputStreamReader fileReader = new InputStreamReader(new FileInputStream("D:\\ Test cases.txt"), StandardCharsets.UTF_8);
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    int data;
    char[] chars = new char[1024];
    while((data = fileReader.read(chars)) ! = -1) {
        charArrayWriter.write(chars, 0, data);
    }
    System.out.println(charArrayWriter.toString());
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

StringReader, StringWriter

StringReader and StringWriter are similar to CharArrayReader and CharArrayWriter except that they use strings and StringBuffers instead of char arrays. They are essentially the same

try {
    InputStreamReader fileReader = new InputStreamReader(new FileInputStream("D:\\ Test cases.txt"), StandardCharsets.UTF_8);
    StringWriter stringWriter = new StringWriter();
    int data;
    char[] chars = new char[1024];
    while((data = fileReader.read(chars)) ! = -1) {
        stringWriter.write(chars, 0, data);
    }
    System.out.println(stringWriter.toString());
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

BufferedReader, BufferedWriter

The use of character buffered streams also requires attention to the refresh buffer

try {
    FileReader fileReader = new FileReader("D:\\ Test cases.txt");
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    int data;
    char[] chars = new char[1024];
    while((data = bufferedReader.read(chars)) ! = -1) {
        System.out.println(new String(chars, 0, data)); }}catch (IOException e) {
    e.printStackTrace();
}
try {
    FileWriter fileWriter = new FileWriter("D:\\ Test cases.txt");
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write("This is a character buffer stream, refresh the buffer.");
    bufferedWriter.flush();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

PrintWriter

try {
    PrintWriter printWriter = new PrintWriter("D:\\ Test cases.txt", StandardCharsets.UTF_8);
    printWriter.write("This is the printout stream.");
    printWriter.write("Can write argument \n number name directly, also support buffer");
    // The character print-out stream needs to flush the buffer manually
    printWriter.flush();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

The standard flow

The Scanner class is a standalone Java class that accepts IO stream data and parses the output

In Java, system. out is one of the standard streams, the standard output stream

This corresponds to the standard input stream, system.in, which is commonly used to receive incoming data

Scanner scanner = new Scanner(System.in);
System.out.println("Receive standard input stream from keyboard.");
String str = scanner.next();
System.out.println(str);
Copy the code

InputStream and OutputStream

Byte InputStream InputStream

  • read(): Reads the next byte of data from the input stream, or -1 if read to the end
  • read(byte[] b): Reads arbitrary bytes from the input stream and stores them in a buffer
  • read(byte[] b, int off, int len): Reads len bytes of data into a byte array
  • close(): Closes the input stream and frees resources

Byte OutputStream OutputStream

  • write(byte[] b): writes b.length bytes from the specified byte array to this output stream
  • write(byte[] b, int off, int len): Writes len bytes from the specified byte array, starting with offset OFF, to the output stream
  • write(int b): writes the specified byte to the output stream
  • flush(): Flushes this output stream and forces any buffered output bytes to be written out
  • close(): Closes this output stream and releases any system resources associated with this stream

InputStream and OutputStream exist as abstract parent classes of byte streams. See the implementation later

A FileInputStream, FileOutputStream

FileInputStream and OutputStream

A file byte stream is a node stream that can read and write data directly

FileOutputStream: Writes data to a disk

Single-byte write

try {
    FileOutputStream stream = new FileOutputStream("D:/ test cases.txt");
    // A run of the main program is treated as a write
    stream.write('H');
    stream.write('W');
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Multibyte writes, in the form of a byte array

try {
    FileOutputStream stream = new FileOutputStream("D:/ test cases.txt");
    String str = "String of multiple characters";
    // Convert a string to a byte array
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    stream.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Single-byte read

try {
    FileInputStream stream = new FileInputStream("D:/ test cases.txt");
    int data;
    while((data = stream.read()) ! = -1) {
        // Convert the integer to the corresponding character
        System.out.print((char) data); }}catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Multibyte read

try {
    FileInputStream stream = new FileInputStream("D:/ test cases.txt");
    int data;
    byte[] bytes = new byte[1024];
    while((data = stream.read(bytes)) ! = -1) {
        // A maximum of 1024 characters can be output at one time
        System.out.print(new String(bytes, 0, data)); }}catch (IOException e) {
    e.printStackTrace();
}
Copy the code

File byte stream, file copy

try {
    FileInputStream inputStream = new FileInputStream("D:/ test cases.txt");
    FileOutputStream outputStream = new FileOutputStream("D:/ Test cases-12.txt");
    int data;
    byte[] bytes = new byte[1024 * 4];
    while((data = inputStream.read(bytes)) ! = -1) {
        // Print the content while writing the data
        System.out.print(new String(bytes, 0, data));
        outputStream.write(bytes, 0, data); }}catch (IOException e) {
    e.printStackTrace();
}
Copy the code

ByteArrayInputStream, ByteArrayOutputStream

In the previous file byte stream, there was a problem that the file data could not be read all at once

To put it simply, if a character happens to be split into two byte arrays, the output may be garbled

ByteArrayInputStream, ByteArrayOutputStream, is a file byte stream set up a buffer, can store each read data, the last output

try {
    FileInputStream inputStream = new FileInputStream("D:\\ Test cases.txt");
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    byte[] bytes = new byte[1024];
    int len;
    while((len = inputStream.read(bytes)) ! = -1) {
        // Stores data read by the file byte stream
        arrayOutputStream.write(bytes, 0, len);
    }
    // When the last read is finished, output once
    System.out.println(arrayOutputStream.toString(StandardCharsets.UTF_8));
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

DateInputStream, DateOutputStream

In the previous byte stream, data was only read and written in bytes

DateInputStream and DateOutputStream are Java classes that can be read and written with different types, such as int and long

Here, an instance object of a Java class is used as an example to read the way it is written

The Person class

public class Person {
    private String name;
    private Integer age;

    public Person(a) {}public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge(a) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "Person{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code

Writes Java class objects to hard disk

Person person = new Person("里斯".23);
try {
    FileOutputStream outputStream = new FileOutputStream("D:\\ Test cases.txt");
    DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
    dataOutputStream.writeUTF(person.getName());
    dataOutputStream.writeInt(person.getAge());
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Read Java class objects into memory

try {
    FileInputStream inputStream = new FileInputStream("D:\\ Test cases.txt");
    DataInputStream dataInputStream = new DataInputStream(inputStream);
    String name = dataInputStream.readUTF();
    int age = dataInputStream.readInt();
    System.out.println(name);
    System.out.println(age);
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

It is clear that the byte stream is not only transmitted in bytes, but can also be written and read directly from Java classes

This involves the serialization mechanism of Java objects, which can be found in files written to data in the form of garbled text

BufferedInputStream, BufferedOutputStream

BufferedInputStream and BufferedOutputStream are byte buffer input streams that provide buffer support for byte reads and writes

Simply understood, a file byte stream wrapped by a byte buffer stream can temporarily cache read and written data, and finally output and written data

You might think of buffer byte streams as similar to byte array streams, but byte array streams have no buffers inside them, just functional similarities

try {
    FileInputStream inputStream = new FileInputStream("D:/ test cases.txt");
    FileOutputStream outputStream = new FileOutputStream("D:/ Test cases-12.txt".true);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
    int data;
    byte[] bytes = new byte[1024];
    while((data = bufferedInputStream.read(bytes)) ! = -1) {
        System.out.print(new String(bytes, 0, data));
        bufferedOutputStream.write(bytes, 0, data);
    }
    // Flush the buffer, otherwise data will not be written to the hard disk
    bufferedOutputStream.flush();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Note that when data is written to disk, the buffer flush() must be flushed.

Buffer byte streams exist so that frequent reads and writes are not needed, but buffer byte streams cannot manipulate data directly. They are processing streams, not node streams