Java IO character stream

Character stream Java provides some character...
Character stream
IO exception handling

Character stream

Java provides some character stream classes to read and write data in character units, which are specially used for processing text files.

Character input stream (Reader)

java.io.Reader Abstract class is a super class representing all classes used to read character stream, which can read character information into memory. It defines the basic common function method of character input stream.

  • public int read(): read a character from the input stream.
  • public int read(char[] cbuf): read some characters from the input stream and store them in the character array cbuf.
  • public void close(): closes the flow and releases any system resources associated with the flow.
FileReader class

java.io.FileReader Class is the class used to read character files. The system default character encoding and default byte buffer are used during construction.

Construction method Constructor Description FileReader(File file) Create a new FileReader, giving the File object to read. FileReader(String fileName) Create a new FileReader, giving the name of the file to read.

The FileReader class does not write its own methods. It inherits the methods of the parent class InputStreamReader.

use

The use steps are almost the same as the file byte input stream! There are also three read methods

method describe int read() Read a data byte from this input stream. int read(byte[] b) Read up to b.length bytes of data into a byte array from this input stream. int read(byte[] b, int off, int len) Read up to len bytes of data into a byte array from this input stream. void close() Close this file input stream and free all system resources associated with this stream.

example

package characterstream; import java.io.FileReader; import java.io.IOException; public class TestReader { public static void main(String[] args) throws IOException { // 1. Create FileReader object FileReader fr = new FileReader("test.txt"); // 2. Use read() method to read characters one by one int len = 0; while ((len = fr.read()) != -1) { System.out.println((char)len); } // 3. Release resources fr.close(); } }

Character output stream (Writer)

java.io.Writer Abstract classes are superclasses that represent all classes used to write out character streams, writing out the specified character information to the destination.

It defines the basic common function method of byte output stream.

  • void write(int c) writes a single character.
  • void write(char[] cbuf) writes a character array.
  • Abstract void write (char [] cbuf, int off, int len) writes a part of the character array, the start index of the off array, and the number of characters written by Len.
  • void write(String str) writes a string.
  • void write(String str, int off, int len) writes a part of the string, the start index of the off string, and the number of characters written by Len.
  • void flush() flushes the buffer for the stream.
  • void close() closes the stream, but refreshes it first.
FileWriter class

java.io.FileWriter Class is a convenient class for writing characters to files. The system default character encoding and default byte buffer are used during construction.

Function: write character data in memory to the destination file

Construction method Constructor Description FileWriter(File file) Create a new FileWriter, given the File object to read. FileWriter(File file, boolean append) Construct a FileWriter object for a File object. append appends content to true. FileWriter(String fileName) Create a new FileWriter, giving the name of the file to read. FileWriter(String fileName, boolean append) Constructs a FileWriter object with a given filename. append appends content to true. FileWriter(FileDescriptor fd) Constructs the FileWriter object associated with the file descriptor. Use steps
  1. Create the FileWriter object, bind the destination to be written in the construction method
  2. write the data into the memory buffer by using the method in FileWriter (there is a process of converting a character into a byte)
  3. Use the flush method of the FileWriter object to refresh the data in the memory buffer to the file.! The difference with byte output stream is here!
  4. Free resources (the data in the memory buffer will be flushed to the file before closing resources)
package characterstream; import java.io.FileWriter; import java.io.IOException; public class TestWriter { public static void main(String[] args) throws IOException { // 1. Create the FileWriter object and bind the destination to be written in the construction method FileWriter fw = new FileWriter("test.txt"); // 2. Use the method write in FileWriter to write the data to the memory buffer (there is a process of converting a character to a byte) fw.write('0'); fw.write("\r\n"); char[] buf = {'a', 'b', 'c', 'd', 'e'}; fw.write(buf); fw.write("\r\n"); fw.write(buf,0,3); fw.write("\r\n"); fw.write("233"); fw.write("\r\n"); fw.write("123456",3,3); fw.write("\r\n"); // 3. Use the flush method of the FileWriter object to refresh the data in the memory buffer to the file.! The difference with byte output stream is here! fw.flush(); // 4. Release resources (the data in the memory buffer will be flushed to the file before closing resources) fw.close(); } }

Note that the file character output class can write strings directly, while the file byte output stream needs to convert strings into byte arrays.

test.txt content

0 abcde abc 233 456

IO exception handling

Before JDK7

In the previous entry practice, we always threw exceptions, which we can't handle in actual development. We recommend using try...catch...finally code block,

Handling exception part, code usage demonstration:

package characterstream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * jdk7 Previous IO exception handling */ public class CopyJDK7 { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("data1.txt"); fw = new FileWriter("data2.txt"); // Note that this is no longer a byte stream, not a byte [] char[] bytes = new char[1024]; int len = 0; while ((len = fr.read(bytes)) != -1) { fw.write(bytes, 0, len); fw.flush(); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } if (fr != null) { try { fr.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } } }

Look at so many braces, too much impact on the readability of the code!

JDK7 processing (extended knowledge)

JDK7 optimized try with resource statement, which ensures that each resource is closed at the end of the statement.

The so-called resource refers to the object that must be closed after the program is completed.

package characterstream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * jdk7 New features of: * try (Create a flow object statement. If multiple flows are created, use ';' to separate them.){ * // Read and write data * } catch (IOException e) { * // exception handling * } */ public class CopyJDK7 { public static void main(String[] args) { // The new feature of JDK7, which adds a bracket after the try and defines the flow object in it, will automatically release resources try (FileReader fr = new FileReader("data1.txt"); FileWriter fw = new FileWriter("data2.txt")) { // Logic code unchanged, definition advanced char[] bytes = new char[1024]; int len = 0; while ((len = fr.read(bytes)) != -1) { fw.write(bytes, 0, len); fw.flush(); } } catch (IOException e) { System.out.println(e.getMessage()); } System.out.println("copy complete"); } }

JDK9 has also made some improvements, but if it's not easy to use, it won't be written

31 May 2020, 06:46 | Views: 4441

Add new comment

For adding a comment, please log in
or create account

0 comments