Java IO knowledge sorting (IV. character operation)

Java IO. Character operation

Character stream

Sometimes there are problems reading text files using byte streams. For example, when encountering Chinese characters, garbled code may appear, because storing these characters requires multiple bytes. Java IO provides a character stream class to read and write data in the unit of characters (characters in java are encoded in Unicode, and one character accounts for 2 bytes), which is used to process text files.

Writer

Writer is an abstract class, which is the base class of all classes representing the character output stream, and writes the specified character information to the destination. It defines the basic functions and methods of character output stream.

  • void write(int c): write a single character.
  • void write(char[] cbuf): writes a character array.
  • abstract void write(char[] cbuf, int off, int len): write a part of the character array. Off is the starting index of the array, and Len represents the length written from the starting index (i.e. the number of characters).
  • void write(String str): writes a string.
  • void write(String str, int off, int len): write a part of the string. Off is the starting index of the array, and Len represents the length written from the starting index (i.e. the number of characters).
  • void flush(): flush the buffer of the stream.
  • void close(): close the stream, but refresh it first.

FileWriter

FileWriter is a typical implementation class of Writer, which is used to write characters to files. The system default character encoding and default byte buffer are used during construction.
Construction method:

  • FileWriter (File): create a new FileWriter and pass in the File object to be read.
  • FileWriter(String name): create a new FileWriter and pass in the name of the file to be read.
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class WriterTest {
    public static void main(String[] args) throws IOException {
        Writer writer = new FileWriter("C:\\Users\\Administrator\\Desktop\\writerTest.txt");
        //Writing a character can use its encoding or write directly to the character itself
        writer.write(97);//Result a
        writer.write('b');//Results a,b
        //Write character array
        char[] text = {'c', 'd'};
        writer.write(text);//Results a,b,c,d
        
        //Write string
        String str = "abed, I see a silver light,\n" +
                "It's suspected to be frost on the ground.\n" +
                "look at the bright moon,\n" +
                "Bow your head and think of your hometown.";
        writer.write(str);
        writer.close();
    }

Code after exception handling:

    public static void main(String[] args) {
        Writer writer = null;
        try {
            writer = new FileWriter("C:\\Users\\Administrator\\Desktop\\writerTest.txt");
            //Writing a character can use its encoding or write directly to the character itself
            writer.write(97);//Result a
            writer.write('b');//Results a,b
            //Write character array
            char[] text = {'c', 'd'};
            writer.write(text);//Results a,b,c,d
            
            //Write string
            String str = "abed, I see a silver light,\n" +
                    "It's suspected to be frost on the ground.\n" +
                    "look at the bright moon,\n" +
                    "Bow your head and think of your hometown.";
            writer.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Reader

Reader is an abstract class. It is the base class representing all classes of character input stream. It can read character information into memory. It defines the basic functions and methods of character input stream.

  • public void close(): close the flow and release the associated system resources.
  • public int read(): reads a character from the input stream. If eof (last file) is read, - 1 is returned.
  • public int read(char[] cbuf): read cbuf length characters from the input stream at a time and store them in the character array cbuf. Returns the number of valid characters read. If eof (the last file) is read, it returns - 1.
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class ReaderTest {
    public static void main(String[] args) throws IOException {
        Reader reader = new FileReader("C:\\Users\\Administrator\\Desktop\\writerTest.txt");
        //Read by single character
//        int ch;
//        while ((ch = reader.read()) != -1) {
//            char text = (char) ch;
//            System.out.print(text);
//        }

        //Read by character array
        char[] chars = new char[5];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = reader.read(chars)) != -1) {
            String text = new String(chars, 0, len);
            sb.append(text);
        }
        System.out.println(sb);
        reader.close();

        //Output results
        /*
        abcd abed, I see a silver light,
        It's suspected to be frost on the ground.
        look at the bright moon,
        Bow your head and think of your hometown.
        */
    }
}

Code after exception handling:

public class ReaderTest {
    public static void main(String[] args){
        Reader reader = null;
        try {
            reader = new FileReader("C:\\Users\\Administrator\\Desktop\\writerTest.txt");
            //Read by single character
//        int ch;
//        while ((ch = reader.read()) != -1) {
//            char text = (char) ch;
//            System.out.print(text);
//        }

            //Read by character array
            char[] chars = new char[5];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = reader.read(chars)) != -1) {
                String text = new String(chars, 0, len);
                sb.append(text);
            }
            System.out.println(sb);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //Output results
        /*
        abcd abed, I see a silver light,
        It's suspected to be frost on the ground.
        look at the bright moon,
        Bow your head and think of your hometown.
        */
    }
}

Keywords: Java Back-end

Added by realjumper on Wed, 08 Dec 2021 20:21:23 +0200