Java input and output stream related usage

Because of the frequent use of input and output streams during data interaction. Record the relevant operations here.

1. File input/output stream (FileInputStream/FileOutputStream class)

Common construction methods:
FileInput(String name);
FileOutputStream(File file);

//创建文件对象
File file = new File("word.txt");
//创建FileOutputStream对象
FileOutputStream out=new FileOutputStream(file);
//创建byte字节
byte send[]="123.".getbyte();
//将数据写入输出流
out.write(send);
out.close();
/***********************************/
//创建FileInputStream对象
FileInputStream in = new FileInputStream(file);
//创建1024字节位的数组储存数据
byte receive[]=new byte[1024]//从输入流读取数据
int len=in.read(receive);
//输出文件信息
System.out.println("文件中的信息"+new String(receive,0,len);
in.close();

It should be noted that since Chinese characters occupy two bytes, garbled characters may appear when using byte streams. At this time, Reader/Writer character streams are generally used. FileReader/FileWriter corresponds to FileInputStream/FileOutputStream. The difference is that as long as the stream is not closed, the former will continue to read the rest of the source in order until the end of the source or the source is closed.

Two, buffered input/output stream (BufferedInputStream/BufferedOutputStream)

It can be used to create a cache area to achieve the purpose of optimizing performance. The BufferedInputStream class has two constructors.
BufferedInputStream(InputStream in); //Create a cache stream with 32 bytes
BufferedOutputSteam(InputSream in,int size) //Create
the flush() method according to the specified size to force the data output of the buffer area, only for OutputStream A subclass of .

The same BufferedReader and BufferWriter also have a caching mechanism.
Common methods of the BufferedReader class are as follows:

read(): read a single character.
readLine(): Reads a line of text and returns it as a string, or null if there is no data to read.
write(String s, int off, int len): Write a certain part of the string.
flush(): Flushes the stream's cache.
newLine(): Write a line separator.

Others include data input\output streams, zip compression input\output streams .

Guess you like

Origin blog.csdn.net/qq_44706002/article/details/103254841