JAVA basics-IO stream (two) character stream, byte stream copy, definition of character array, ReadLine, newLine(), LineNumberReader

1. Concept and classification

  1. Concept
    IO stream is used to process data transmission between devices
    • The operation of Java on data is through the way of streaming
    • The classes used by Java to manipulate streams are all in the IO package
    • Flow is divided into two types according to flow direction: input flow and output flow.
    • Streams are divided into two types according to operation types:
      • Byte stream : The byte stream can manipulate any data, because any data in the computer is stored in the form of bytes
      • Character stream: Character stream can only operate on pure character data, which is more convenient.
        The following chapters introduce the byte stream and character stream of IO stream
  2. Common parent class of IO stream
  • The abstract parent class of byte stream:
    InputStream
    OutputStream
  • Abstract parent class of character stream:
    Reader
    Writer
  1. IO program writing
  • Before use, import the classes in the IO package
  • When in use, perform IO exception handling
  • After use, release resources. The
    following must be understood well, we are input and output relative to memory, not from the perspective of the user, that is, FileInputStream performs input. It is memory to get elements from the document we write. Input into its own buffer, which means that it needs to be read. And we want to output something from the java buffer, that is, perform an OutputStream, and write what we want from the buffer.
    The following describes the character stream

Two, character stream FileReader

1. What is the character stream

  • Character stream is an IO stream that can directly read and write characters
  • To read a character in a character stream, you must first read the byte data, and then convert it into a character. If you want to write a character, you need to convert the character to a byte and then write it out.

2. FileReader
case: Create a new xxx.txt file under this project. Write content inside.

FileReader fileReader =new FileReader("xxx.txt");
		int c;
		while ((c=fileReader.read())!=-1) {
    
    
//通过项目默认的码表一次读取一个字符
			System.out.print((char)c);
		}
		fileReader.close();

The effect is as follows:
Insert picture description here

Three, character stream FileWriter

FileWriter fileWriter =new FileWriter("yyy.txt");
		fileWriter.write("大家好,我是小学生");	//写字符串
		fileWriter.write(97); 				//写一个字符
		fileWriter.close();

The effect is as follows:
Insert picture description here

Fourth, the copy of the character stream

FileReader fileReader =new FileReader("xxx.txt");
	FileWriter fileWriter =new FileWriter("zzz.txt");
	int c;
	while ((c=fileReader.read())!=-1) {
    
    
		fileWriter.write(c);		//不用char强转
	}
	fileReader.close();	
	//Writer中有一个2k的小缓冲区,如果不关流,就会将内容写到缓冲区里面
	fileWriter.close();	//关流,会将缓冲区的内容写入

The effect is as follows:
Insert picture description here

tips: If we do not have a write shutdown method at this time, we will find that the data has not been written. It is because there is a small 2k buffer in Writer, if you do not close the stream, the content will be written into the buffer

Five, when to use character stream

  • The character stream can also copy text files, but it is not recommended. Because the bytes are converted into characters when reading, and the characters are converted back to bytes when writing. There is a conversion process in the middle. And FileInputStream accepts bytes directly and outputs bytes.
  • A character stream can be used when the program needs to read a piece of text, or when it needs to write a piece of text. (Read only or write only)
  • When reading, it is read according to the size of the characters, and there will be no half of Chinese
  • When writing, you can write the string directly without converting it to a byte array

6. Whether the character stream can copy files that are not plain text

  • Do not copy files that are not plain text
  • Because the bytes are converted into characters when reading, during the conversion process, the corresponding characters may not be found, it will be replaced by ?, and the characters will be converted into bytes when writing out.
  • If it is?, write it out directly, so that the file after writing out will be messed up and can't be seen

Seven, copy of custom character array

FileReader fileReader =new FileReader("xxx.txt");
FileWriter fileWriter=new FileWriter("yyy.txt");
		char[] arr= new char[1024];
		int len;
		while ((len=fileReader.read(arr))!=-1) {
    
    	
//将文件上的数据读取到字符数组中
			fileWriter.write(arr,0,len);			
//将字符数组中的数据写到文件上
		}
		fileReader.close();
		fileWriter.close();

The effect is as follows:
Insert picture description here

8. Buffered character stream

  • The read() method of BufferedReader will read several characters to the buffer at a time when reading characters, and then return them to the program one by one, reducing the number of times to read files and improving efficiency
  • The write() method of BufferedWriter writes characters to the buffer first, and then writes to the file when the buffer is full, reducing the number of times to write files and improving efficiency
BufferedReader bufferedReader =new BufferedReader(new FileReader("xxx.txt"));
BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("yyy.txt"));
		int c;
while ((c=bufferedReader.read())!=-1) {
    
    
				bufferedWriter.write(c);
}
	bufferedReader.close();
	bufferedWriter.close();

Nine, readLine() and newLine() methods

  • The readLine() method of BufferedReader can read a line of characters (not including the newline symbol)
    .
  • BufferedWriter's newLine() can output a cross-platform newline symbol "\r\n"
BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("aaa.txt"));
		String line;
		while ((line=bufferedReader.readLine())!=null) {
    
    
			bufferedWriter.write(line);
			bufferedWriter.newLine();
			//或者用下面方法
			bufferedWriter.write("\r\n");
		}
		bufferedReader.close();

tips: Note: bufferedWriter.newLine(); This method can be used across platforms. But bufferedWriter.write("\r\n"); only works under windows system. And note that readLine() can read the characters in each line of the text, excluding the newline symbol.

十、 LineNumberReader

  • LineNumberReader is a subclass of BufferedReader, has the same function, and can count line numbers
  • Call the getLineNumber() method to get the current line number
  • Call the setLineNumber() method to set the current line number
LineNumberReader lineNumberReader =new LineNumberReader(new FileReader("zzz.txt"));
		String line;
//如果加上这一行代码
		lineNumberReader.setLineNumber(100);	
//会从第101行往后书写
while ((line=lineNumberReader.readLine())!=null) {
    
    
			System.out.println(lineNumberReader.getLineNumber()+":"+line);
		}
		lineNumberReader.close();

At this point we visit the document:
Insert picture description here
if we lineNumberReader.setLineNumber(100); we will start reading from line 100

11. Use the specified code table to read and write characters

  • FileReader uses the default code table to read the file. If you need to use the specified code table to read, you can use InputStreamReader (byte stream, code table)
  • FileWriter uses the default code table to write out files. If you need to use the specified code table to write out, you can use OutputStreamWriter (byte stream, code table)
    case:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("UTF-8.txt"), "UTF-8"));
//高效的用指定的编码表读
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("GBK.txt"), "GBK"));
//高效的用指定的编码表写
int ch;
while((ch = br.read()) != -1) {
    
    
bw.write(ch);
}

br.close();
bw.close();

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/108805338