JAVA basics-IO stream (1) byte stream, four copy modes, byte stream copy pictures, mp3 mode

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 to 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 chapter introduces byte streams

Two, FileInputStream (for input)

Because InputStream is an abstract class, it cannot generate objects by itself. So learn its first subclass FileInputStream.
For the read() method under FileInputSteam, first we need to create a new txt file under this project and name it XXX.txt. Write three letters abc in it
Insert picture description here
Case:

FileInputStream fileInputStream =new FileInputStream("xxx.txt");
		int x =fileInputStream.read(); 	//创建流对象
		System.out.println(x);			//从硬盘上读取一个字节
		int y =fileInputStream.read();
		System.out.println(y);
		int z =fileInputStream.read();
		System.out.println(z);
		int b =fileInputStream.read();
		System.out.println(b);
		fileInputStream.close();		//关闭释放资源

The effect is as follows:
Insert picture description here
we find that every time we execute a read method, only the number corresponding to the code table corresponding to a letter is output. But when we read the last number and found that the return value is -1. So we can optimize

FileInputStream fileInputStream =new FileInputStream("xxx.txt");
	int b;
	while ((b=fileInputStream.read())!=-1) {
    
    
		System.out.println(b);
	}
	fileInputStream.close();

3. Why is the return value of the read() method int

The read() method reads a byte. Why is the return int instead of byte?
Because the byte input stream can operate on any type of file, such as pictures and audio, these files are stored in binary form at the bottom layer. Each read returns byte, because byte occupies one byte, and one byte consists of 8 binary numbers. It is possible to encounter 111111111 (-1's complement) when reading the middle,
then this 11111111 is byte type -1, our program will stop reading when it encounters -1, and the following data will not be read, so When reading, use the int type to receive, if 11111111 will add 24 0s in front of it to make up 4 bytes, then the byte type -1 will become the int type 255 (00000000 00000000 00000000 11111111). This can be guaranteed The entire data is read, and the end tag -1 (equal to -1 does not need to be transferred) is int type.

Four, FileOutputStream (for output)

FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt");
		fileOutputStream.write(97);		
		//虽然写出的是一个int数。但是到文件上的是一个字节 会自动去除前三个8位
		fileOutputStream.write(98);
		fileOutputStream.write(99);
		fileOutputStream.close();

At this point we will see a new yyy.txt under the project path. And wrote some content, the
effect is as follows:
Insert picture description here

5. Added FileOutputStream

If we annotate the content written before, we will find the content written later to be modified.
Insert picture description hereIf you want to output, abcd. Indicates that we need to append. The content of the file will not be modified.

FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt",true);
		fileOutputStream.write(97);		
		//虽然写出的是一个int数。但是到文件上的是一个字节 会自动去除前三个8位
		fileOutputStream.write(98);
		fileOutputStream.write(99);
		fileOutputStream.write(100);
		fileOutputStream.close();

The effect is as follows:
Insert picture description here
the application scenario of this function, we can add the content of the chat record when looking up the chat record.

Six, copy pictures (the first copy method)

First we need a picture and put the picture under the project. The change line code is the mainstream code of the IO stream. If we copy mp3, we only need to change the value in the brackets. But the efficiency is too slow, we need to read byte by byte.

FileInputStream fileInputStream =new FileInputStream("6.jpg");//创建输入流对象
FileOutputStream fileOutputStream =new FileOutputStream("copy.jpg");//创建输出流对象
		int b;
	while((b=fileInputStream.read())!=-1) {
    
    			
//在不断地读取每一个字节
			fileOutputStream.write(b);					
//将每一个字节写出
		}
		fileOutputStream.close();
		fileInputStream.close();

At this time, our pictures will be copied over. But the efficiency is too slow, we need to read byte by byte.
So we introduce the method of reading the entire file. That is, the available() method

7. Available() method of byte array copy (the second copy method)

FileInputStream fileInputStream =new FileInputStream("6.jpg");
		FileOutputStream fileOutputStream =new FileOutputStream("copy.jpg");
		int len =fileInputStream.available();
		System.out.println(len);
		fileInputStream.close();
		fileOutputStream.close();

The effect is as follows:
Insert picture description here
the number is the byte value occupied by the file, bytes.
So, we can upgrade.

FileInputStream fileInputStream =new FileInputStream("6.jpg");
		FileOutputStream fileOutputStream =new FileOutputStream("copy.jpg");
byte[] arr=new byte[fileInputStream.available()];	
//创建与文件一样大小的字节数组
		fileInputStream.read(arr);							
//将文件上的字节读取到内存中
		fileOutputStream.write(arr);						
//将字节数组中的字节数据写到文件上
		fileInputStream.close();
		fileOutputStream.close();

The effect is as follows:
Insert picture description here
In development, it is not recommended to use this method array to copy files. When the file is too large, it may cause memory overflow.

8. Define the number of groups (the third copy method)

FileInputStream fileInputStream =new FileInputStream("xxx.txt");
		byte[] arr=new byte[2];
		int a =fileInputStream.read(arr);
		System.out.println(a);
		for (byte b : arr) {
    
    
			System.out.println(b);
		}
		System.out.println("--------------");
		int c=fileInputStream.read(arr);
System.out.println(c);
		for (byte b : arr) {
    
    
			System.out.println(b);
		}
		fileInputStream.close();

The effect is as follows:
Insert picture description here
at this time we found that we can only read two numbers. When we read it for the first time, we will read ab (97 98) in a limited amount. Then, when we read two numbers again, c will occupy the position of a, so 99 98 will be read.
So when we read and write, we will perform the following operations

FileInputStream fileInputStream =new FileInputStream("xxx.txt");
FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt");
		byte []arr =new byte[2];
		int len;
		while((len=fileInputStream.read(arr))!=-1) {
    
    
			fileOutputStream.write(arr, 0, len);
		}
		fileInputStream.close();
		fileOutputStream.close();

The effect is as follows: Insert picture description here
Standard writing method: Because we generally read data not two by two, but willReading in multiples of 1024,
So to upgrade:

FileInputStream fileInputStream =new FileInputStream("xxx.txt");
		FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt");
		byte[] arr=new byte[1024*8];
		int len;
		while((len=fileInputStream.read(arr))!=-1) {
    
    	
		//如果忘记加arr,返回的就不是读取的字节个数,而是字节的码表值
			fileOutputStream.write(b, 0, len);
		}

The effect is the same, but the efficiency will be doubled.

Nine, BufferedInputStream and BufferOutputStream copy (fourth copy method)

Buffer thinking

  • The speed of byte stream reading and writing an array at a time is obviously much faster than the speed of reading and writing one byte at a time.
  • This is the addition of buffer effects such as arrays. When Java itself was designed,
  • This design idea is also considered (explained later in the decorative design pattern), so a byte buffer stream is provided

BufferedInputStream

  • BufferedInputStream has a built-in buffer (array)
  • When reading a byte from BufferedInputStream
  • BufferedInputStream will read 8192 from the file at one time, store them in the buffer, and return one to the program
  • When the program reads again, there is no need to find the file, it is directly obtained from the buffer
  • Until all the buffers have been used, 8192 are read from the file again

BufferedOutputStream
BufferedOutputStream also has a built-in buffer (array)

  • When the program writes bytes to the stream, it will not directly write to the file, but first write to the buffer
  • Until the buffer is full, BufferedOutputStream will write the data in the buffer to the file at one time.
FileInputStream fileInputStream =new FileInputStream("6.jpg");			
//创建输入流对象6.jpg	
FileOutputStream fileOutputStream =
new FileOutputStream("copy.jpg");	
//创建输出流对象copy.jpg
BufferedInputStream bufferedInputStream =
new BufferedInputStream(fileInputStream);
//创建缓冲区对象,对输入流进行包装让其更加强大
BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(fileOutputStream);
//创建缓冲区对象,对输出流进行包装让其更加强大
		int b;
		while ((b=bufferedInputStream.read())!=-1) {
    
    
			bufferedOutputStream.write(b);
		}
		bufferedInputStream.close();
		bufferedOutputStream.close();
  • Which is faster to read and write small arrays or read with Buffered?
    • Define a small array if the size of 8192 bytes is compared with Buffered
    • It is slightly better to define a small array, because the read and write operations are the same array
    • And Buffered operates on two arrays

Ten, the difference between flush and close methods

flush() method

  • Used to refresh the buffer, it can be written out again after refreshing

close() method

  • Used to close the stream and release resources, if it is the close() method of the stream object with a buffer, it will not only close the stream, but also flush the buffer before closing the stream, and can't write out after closing
  • Simply put, it has a refresh function. Before closing, it will refresh the buffer again. In case there is an extra 8192 bytes in the buffer, it may be 500 bytes. It will refresh the buffer for the last time. Refresh all the bytes in the file, then close

11. Byte stream reading and writing Chinese

The problem of reading Chinese from byte stream: When the byte stream is reading Chinese, it is possible to read half of Chinese, causing garbled
byte stream to write Chinese: the byte stream directly manipulates the byte, so the Chinese is written The character string must be converted to byte output. Write a carriage return and line feed. write("\r\n".getBytes())

FileInputStream fileInputStream =new FileInputStream("yyy.txt");
		byte [] arr=new byte[3];
		int len;
		while ((len=fileInputStream.read(arr))!=-1) {
    
    
			System.out.println(new String(arr,0,len));
		}
		fileInputStream.close();

The effect is as follows:
Insert picture description here
because a word in Chinese is two bytes, and the length of the array we read is three bytes, a word will be split in half to read, resulting in unsuccessful recognition.

FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt");
		fileOutputStream.write("我在学习字节流".getBytes()); //把字节数组写出去
		fileOutputStream.close();

The effect is as follows:
Insert picture description here
because we store the written Chinese directly into the array, so there will be no problems

Twelve, try-catch-finally wording of IO stream

jdk1.6 and above:

public static void demo1() throws FileNotFoundException, IOException {
    
    
	FileInputStream fileInputStream =null;
	FileOutputStream fileOutputStream =null;
	int b;
	try {
    
    
		fileInputStream =new FileInputStream("xxx.txt");
		fileOutputStream =new FileOutputStream("yyy.txt");
		
		while ((b=fileInputStream.read())!=-1) {
    
    
			fileOutputStream.write(b);
		}
	}finally {
    
    
		try {
    
    
			if (fileInputStream!=null) 
				fileInputStream.close();
			
		}finally {
    
    
			if (fileOutputStream!=null) {
    
    
				fileOutputStream.close();
			}
		}
	}
}

jdk1.7 version and above

try(
				FileInputStream fileInputStream = new FileInputStream("xxx.txt");
				FileOutputStream fileOutputStream =new FileOutputStream("yyy.txt");
				
		){
    
    
			int b;
			while ((b=fileInputStream.read())!=-1) {
    
    
				fileOutputStream.write(b);
			}
		}

Because in jdk1.7 version,Try first use parentheses () to perform input and output stream operationsBecause they will callAutoCloseableInterface. Automatically close the input and output streams. If we want to write a close method by ourselves, we must use this interface

Guess you like

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