Use Java character stream

Character-input stream

Reader class is the parent class of all characters in the input stream class that defines a number of methods that are valid for all subclasses.

Reader common class subclasses as follows.

	CharArrayReader 类:将字符数组转换为字符输入流,从中读取字符。
	
	StringReader 类:将字符串转换为字符输入流,从中读取字符。
	
	BufferedReader 类:为其他字符输入流提供读缓冲区。
	
	PipedReader 类:连接到一个 PipedWriter。
	
	InputStreamReader 类:将字节输入流转换为字符输入流,可以指定字符编码。

InputStream class the same, is also included in the class Reader close (), mark (), skip () and reset () method and the like, can refer to these methods InputStream class.

read Reader class () method

Method name and return value type Explanation
int read() Reads a character from the input stream and converts it to an integer of 0 to 65535. Return -1 indicates that has come to the end of the input stream. In order to improve the efficiency of I / O operations, we recommended to make use of two read () method
int read(char[] cbuf) A plurality of characters read from the input stream, and save them to the parameter cbuf specified character array. The method returns the number of characters read, return -1 indicates the end of the input stream has reached the
int read(char[] cbuf,int off,int len) A plurality of characters read from the input stream, and save them to the parameter cbuf specified character array. Wherein, off specify a starting index start saving data in a character array, len specify the number of characters read. The method returns the number of characters actually read, it will return -1, then the input has reached the end of the stream

Character-output stream

In contrast with the class Reader, Writer class is the parent class of all characters in the output stream , the class has many methods that all subclasses inherit this class are valid.

Writer common class subclasses as follows.

	CharArrayWriter 类:向内存缓冲区的字符数组写数据。
	
	StringWriter 类:向内存缓冲区的字符串(StringBuffer)写数据。
	
	BufferedWriter 类:为其他字符输出流提供写缓冲区。
	
	PipedWriter 类:连接到一个 PipedReader。
	
	OutputStreamReader 类:将字节输出流转换为字符输出流,可以指定字符编码。

Same class OutputStream, Writer class also contains close (), flush () method and the like, which can refer to a method of OutputStream.

Writer class write () method and append () method

Method name and return value type Explanation
void write(int c) Writing a character to the output stream
void write(char[] cbuf) All the characters in the parameter cbuf specified character array written to the output stream
void write(char[] cbuf,int off,int len) The parameter cbuf specified character array several characters written to the output stream. Wherein the specified character array off the starting index, len denotes the number of elements
void write(String str) Write a string to the output stream,
void write(String str, int off,int len) Writing a portion of the character string to the output stream. Wherein the starting offset off in the specified string, len denotes the number of characters
append(char c) Add the parameter c specifies the character to the output stream
append(charSequence esq) Esq add parameters specified character sequence to the output stream
append(charSequence esq,int start,int end) Add the sequence parameter esq specified character sequence to the output stream. Wherein the index of the first character of the subsequence start, end subsequence index of the last character after character, that is to say the content of the sub-sequence comprises a start character index, but the index of the end character is not included

note: Writer class all the way in the case of error will lead to an IOException. After closing a flow, then no further action will produce an error.

Character file input stream

In order to facilitate reading, Java provides a convenient --FileReader class for reading character files. There are two class constructor overloads follows.

	FileReader(File file):在给定要读取数据的文件的情况下创建一个新的 FileReader 对象。其中,file 表示要从中读取数据的文件。
	
	FileReader(String fileName):在给定从中读取数据的文件名的情况下创建一个新 FileReader 对象。其中,fileName 表示要从中读取数据的文件的名称,表示的是一个文件的完整路径。

When creating an object by reading FileReader constructor class, default character encoding and byte-buffer size are set by the system. To specify these values ​​yourself, you can construct an InputStreamReader on FilelnputStream.

note: When you create a FileReader object may cause a FileNotFoundException exception, so need to use try catch statement to catch the exception.

The procedure is identical character stream and byte stream, or the stream is first input to create an output stream object, i.e., a connection pipe, establishing a read or write operation is complete, and finally closes the input / output flow channels.

The D: \ content myJava \ HelloJava.java file is read and output to the console, using the code that implements the class FileReader follows:

public class Test {
    public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader("D:/myJava/HelloJava.java"); // 创建FileReader对象
            int i = 0;
            System.out.println("D:\\myJava\\HelloJava.java文件内容如下:");
            while ((i = fr.read()) != -1) { // 循环读取
                System.out.print((char) i); // 将读取的内容强制转换为char类型
            }
        } catch (Exception e) {
            System.out.print(e);
        } finally {
            try {
                fr.close(); // 关闭对象
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

As the above code, first create a character input stream object FileReader fr, the object point D: \ myJava \ HelloJava.java file, a return value and then define the variable i read () method, i.e., the read character received call. In the while loop, reads one character assigned to integer variables i, the loop is exited read until the end of the file (the input stream when the end of the file is read, it returns a value of -1).

Character file output stream

Java provides a convenient class --FileWriter writing character files, the class constructor has the following four overloads.

	FileWriter(File file):在指定 File 对象的情况下构造一个 FileWriter 对象。其中,file 表示要写入数据的 File 对象。
	
	FileWriter(File file,boolean append):在指定 File 对象的情况下构造一个 FileWriter 对象,如果 append 的值为 true,则将字节写入文件末尾,而不是写入文件开始处。
	
	FileWriter(String fileName):在指定文件名的情况下构造一个 FileWriter 对象。其中,fileName 表示要写入字符的文件名,表示的是完整路径。
	
	FileWriter(String fileName,boolean append):在指定文件名以及要写入文件的位置的情况下构造 FileWriter 对象。其中,append 是一个 boolean 值,如果为 true,则将数据写入文件末尾,而不是文件开始处。

When you create a FileWriter object, the default character encoding and the default byte-buffer size are set by the system. To specify these values ​​yourself, you can construct a OutputStreamWriter object on the FileOutputStream.

Create a FileWriter class is not dependent on the presence or absence of a file, if the associated file does not exist, it will automatically generate a new file. Before you create a file, FileWriter will open it as an output when the object is created. If you attempt to open a read-only file, an IOException is thrown.

note: When you create a FileWriter object may cause IOException SecurityException or abnormal, so need to use try catch statement to catch the exception.

Save the user to input a string of four D: \ myJava \ book.txt file. Used herein FileWriter class write () method loops to write data to the specified file, the codes are as follows:

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        FileWriter fw = null;
        try {
            fw = new FileWriter("D:\\myJava\\book.txt"); // 创建FileWriter对象
            for (int i = 0; i < 4; i++) {
                System.out.println("请输入第" + (i + 1) + "个字符串:");
                String name = input.next(); // 读取输入的名称
                fw.write(name + "\r\n"); // 循环写入文件
            }
            System.out.println("录入完成!");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                fw.close(); // 关闭对象
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

As described above the code first creates a point D: \ character file myJava \ book.txt FW file output stream object, and then use the entry for four string loop and calls write () method writes the character string to a specified file. Finally, close the file in character finally statement output stream.

Run the program, according to prompts four strings, as shown below. Then open the D: \ myJava \ book.txt file, you will see the written content.

请输入第1个字符串:
热点要闻
请输入第2个字符串:
个性推荐
请输入第3个字符串:
热搜新闻词
请输入第4个字符串:
本地看点
录入完成!

Character buffer input stream

BufferedReader principal input stream to assist other characters, it is with a buffer, can first batch of data into memory buffers . The next reading operation can obtain data directly from the buffer, each time without the need to read data from a data source and character encoding conversion so that it can improve the efficiency of data reading.

BufferedReader class constructor overloads the following two.

	BufferedReader(Reader in):创建一个 BufferedReader 来修饰参数 in 指定的字符输入流。
	
	BufferedReader(Reader in,int size):创建一个 BufferedReader 来修饰参数 in 指定的字符输入流,参数 size 则用于指定缓冲区的大小,单位为字符。

In addition to providing the buffer is other than a character input stream, the BufferedReader also provides the readLine () method returns a string that contains the contents of the line, but does not contain any string terminator, if the end of the stream is null. the readLine () method of each line of text represents the content reading, when faced linefeed (\ n-), Enter (\ R & lt) directly followed by a carriage return or line feed can be considered a marker line is terminated.

BufferedReader class using the readLine () method read row by row D: \ content myJava \ Book.txt file, and content read in the console printout, as follows:

public class Test {
    public static void main(String[] args) {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("D:\\myJava\\book.txt"); // 创建 FileReader 对象
            br = new BufferedReader(fr); // 创建 BufferedReader 对象
            System.out.println("D:\\myJava\\book.txt 文件中的内容如下:");
            String strLine = "";
            while ((strLine = br.readLine()) != null) { // 循环读取每行数据
                System.out.println(strLine);
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close(); // 关闭 FileReader 对象
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

As the above code, were first created the name for the object and the name of the FileReader fr is BufferedReader br objects, and then call readLine BufferedReader object (the contents of the file read line by line method). If the contents of the file read is Null, that is, to the end of the file shows that have been read, then exit the loop no longer read operation. Finally, the file input stream of characters and character buffered input stream is closed.

Run the program, the output results are as follows:

D:\myJava\book.txt 文件中的内容如下:
热点要闻
个性推荐
热搜新闻词
本地看点

Character buffer output stream

BufferedWriter class mainly used to assist other characters output stream, with the same buffer, the first batch of data can be written to the buffer, when the buffer is full, then data is written to the buffer disposable character output stream, its purpose is to improve the efficiency of data write.

BufferedWriter class constructor overloads the following two.

	BufferedWriter(Writer out):创建一个 BufferedWriter 来修饰参数 out 指定的字符输出流。
	
	BufferedWriter(Writer out,int size):创建一个 BufferedWriter 来修饰参数 out 指定的字符输出流,参数 size 则用于指定缓冲区的大小,单位为字符。

Such a buffer may be provided in addition to the output character stream, but also provides a new method newLine (), the method for writing a line separator. Line separator string is defined by the system property line.separator, and not necessarily a single row (\ n) character.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104711081