Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the JAVA IO system like?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the JAVA IO system, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Byte-based IO operation

Character-based IO operation

As can be seen from the figure above, the entire Java IO system is based on byte stream (InputStream/OutputStream) and character stream (Reader/Writer) as base classes, derived from different data carriers or functions.

- -

IO common class

File stream: FileInputStream/FileOutputStream, FileReader/FileWriter

These four classes specialize in manipulating file streams and are highly similar in usage, except that the first two are operation byte streams and the last two are operation character streams. They all directly manipulate the file stream and interact directly with the underlying OS. So they are also called node flows.

Note that after using the objects of these streams, you need to close the stream objects because the java garbage collector does not actively collect them. However, after Java7, you can open the stream in try () parentheses, and finally the program will automatically close the stream object, eliminating the need for the displayed close.

The following demonstrates the basic usage of these four stream objects

Package io;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class TestIO {public static void FileInputStreamTest () throws IOException {FileInputStream fis = new FileInputStream ("tmp2.txt"); byte [] buf = new byte [1024]; int hasRead = 0 / / read () returns single byte data (byte data can be int directly), but read (buf) returns the number of bytes read, and the real data is saved in buf while ((hasRead = fis.read (buf)) > 0) {/ / convert up to 1024 bytes into strings at a time, where the characters in tmp2.txt are less than 1024 So read it all at once / / number of loops = file characters divided by buf length System.out.println (new String (buf, 0, hasRead)) / * * convert bytes to characters and output them one by one, which can achieve the same effect as above. But if the source file is in Chinese, it may garble for (byte b: buf) {char ch = (char) b; if (ch! ='\ r') System.out.print (ch) } * /} / / close is more secure fis.close () in finally block } public static void FileReaderTest () throws IOException {try (/ / files opened in try (), JVM automatically closes FileReader fr = new FileReader ("tmp2.txt")) {char [] buf = new char [32]; int hasRead = 0 / / each char occupies two bytes, and each character or Chinese character occupies 2 bytes, so no matter how long the buf is, it can always read integral times the length of Chinese characters and will not garbled while ((hasRead = fr.read (buf)) > 0) {/ / if the length of buf is greater than the length of each line of the file, you can output each line completely, otherwise the line will be broken. / / number of loops = number of characters in the file divided by buf length System.out.println (new String (buf, 0, hasRead)); / / same as above / / System.out.println (buf);}} catch (IOException ex) {ex.printStackTrace () }} public static void FileOutputStreamTest () throws FileNotFoundException, IOException {try (/ / opening the file in try () automatically closes FileInputStream fis = new FileInputStream ("tmp2.txt"); FileOutputStream fos = new FileOutputStream ("tmp3.txt");) {byte [] buf = new byte [4] Int hasRead = 0; while ((hasRead = fis.read (buf)) > 0) {/ / write every time you read, write as many fos.write (buf, 0, hasRead) as you read;} System.out.println ("write success");} catch (IOException e) {e.printStackTrace () } public static void FileWriterTest () throws IOException {try (FileWriter fw = new FileWriter ("tmp4.txt")) {fw.write ("Heavenly King cover Tiger\ r\ n"); fw.write ("Baota Town River Devil\ r\ n");} catch (IOException e) {e.printStackTrace () } public static void main (String [] args) throws IOException {/ / FileInputStreamTest (); / / FileReaderTest (); / / FileOutputStreamTest (); FileWriterTest ();}}

Packaging flow: PrintStream/PrintWriter/Scanner

PrintStream can encapsulate (wrap) the node flow object OutputStream that interacts directly with the file, so that programmers can ignore the differences at the bottom of the device and perform consistent IO operations. So this flow is also called a processing flow or a wrapper flow.

PrintWriter can wrap not only byte stream OutputStream, but also character stream Writer

Scanner can wrap the keyboard input and easily convert the keyboard input into the data type we want.

String stream: StringReader/StringWriter

These two manipulate streams that specialize in manipulating String strings, where StringReader can easily read data from String and save it to char arrays, while StringWriter writes string-type data to StringBuffer (because String is not writable).

Translation flow: InputStreamReader/OutputStreamReader

These two classes can convert a byte stream into a character stream, which is called a bridge between a byte stream and a character stream. We often need to use these two classes when reading keyboard input (System.in) or network communication.

Buffer stream: BufferedReader/BufferedWriter, BufferedInputStream/BufferedOutputStream

The official description of Oracle:

Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient.

Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

That is,

IO without Buffered processing means that every read and write request is directly processed by the OS underlying layer, which can lead to very inefficient problems.

The input stream processed by Buffered will read data from an buffer memory area, and the local API will only be called after the buffer is empty (perhaps a single call will populate a lot of data into the buffer).

The output stream processed by Buffered will write the data to the buffer, and the local API will only be called after the buffer is full.

BufferedReader/BufferedWriter can wrap character streams (Reader) as buffered streams, which is the most common practice.

In addition, BufferedReader provides a readLine () that can easily read a line, while FileInputStream and FileReader can only read one byte or one character

So the BufferedReader is also called the row reader.

Package io;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.io.PushbackReader;import java.io.StringReader;import java.io.StringWriter;public class TestIO {public static void printStream () throws FileNotFoundException, IOException {try (FileOutputStream fos = new FileOutputStream ("tmp.txt") PrintStream ps = new PrintStream (fos) {ps.println ("normal string\ n"); / / output object ps.println (new TestIO ());} catch (IOException e) {e.printStackTrace ();} System.out.println ("output complete") } public static void stringNode () throws IOException {String str = "Heavenly King cover Tiger\ n" + "Baota Town River Devil\ n"; char [] buf = new char [32]; int hasRead = 0 / / StringReader will read data try (StringReader sr = new StringReader (str)) {while ((hasRead = sr.read (buf)) > 0) {System.out.print (new String (buf, 0, hasRead));}} catch (IOException e) {e.printStackTrace () } / / because String is an immutable class, when you create a StringWriter, you actually use a StringBuffer as the output node try (StringWriter sw = new StringWriter ()) {sw.write ("Night gives me black eyes\ n"); sw.write ("I use it to find light\ n") / / toString () returns the data in the sw node System.out.println (sw.toString ());} catch (IOException e) {e.printStackTrace ();}} public static void keyIn () throws IOException {try (/ / InputStreamReader is the bridge from byte to char InputStreamReader reader = new InputStreamReader (System.in) / / BufferedReader (Reader in) is the wrapper class BufferedReader br = new BufferedReader (reader) entered by the char type;) {String line = null; while ((line = br.readLine ())! = null) {if (line.equals ("exit")) {/ / System.exit (1) Break;} System.out.println (line);}} catch (IOException e) {e.printStackTrace () }} public static void pushback () throws FileNotFoundException, IOException {try (PushbackReader pr = new PushbackReader (new FileReader ("C:/PROJECT/JavaBasic/PROJECT_JavaBasic/src/io/TestIO.java"), 64)) {char [] buf = new char [32]; String lastContent = ""; int hasRead = 0 While ((hasRead = pr.read (buf)) > 0) {String content = new String (buf, 0, hasRead); int targetIndex = 0; if ((targetIndex = (lastContent + content) .indexOf ("targetIndex = (lastContent + content)") > 0) {pr.unread ((lastContent + content). ToCharArray ()) If (targetIndex > 32) {buf = new char [targetIndex];} pr.read (buf, 0, targetIndex); System.out.println (new String (buf, 0, targetIndex)); System.exit (0) } else {System.out.println (lastContent); lastContent = content;} catch (IOException e) {e.printStackTrace ();}} public static void main (String [] args) throws IOException {printStream (); / / stringNode () / / keyIn (); / / pushback ();}}

Summarize the application scenarios of the above streams:

FileInputStream/FileOutputStream is inefficient when it needs to process the original binary stream byte by byte.

Used when FileReader/FileWriter needs to be processed in groups of characters.

When StringReader/StringWriter needs to deal with strings, it can save strings as character arrays.

PrintStream/PrintWriter is used to wrap FileOutputStream objects, and it is convenient to write String strings directly to files.

Scanner is used to wrap the System.in stream, easily converting the input String string to the required data type

InputStreamReader/OutputStreamReader, a conversion bridge between bytes and characters, used in network communication or when dealing with keyboard input

BufferedReader/BufferedWriter, BufferedInputStream/BufferedOutputStream, buffer streams are used to wrap the latter character stream, improve IO performance, BufferedReader can also easily read a line, simplifying programming.

This is what the JAVA IO system is like, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report