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 a Java IO stream?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what is the Java IO stream". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what the Java IO stream is.

Overview of IO

In this section, I'll try to give an overview of all the classes under the Java IO (java.io) package. More specifically, I will group classes according to their purpose. This grouping will make it easier for you to determine the use of a class or to select a class for a particular purpose in your future work.

Input and output

The terms "input" and "output" are sometimes a little confusing. The input of one application is often the output of another application, so is the OutputStream stream an output stream to the destination or a stream that produces output? Will the InputStream stream output its data to the program that reads the data? Personally, I felt a little confused on the first day of learning Java IO. To dispel this confusion, I tried to give input and output different aliases to conceptually relate to the source and flow of the data.

Java's IO package focuses on reading from the original data source and outputting the original data to the target medium. The following are the most typical data sources and target media:

File pipe network connection memory cache System.in, System.out, System.error (Note: Java standard input, output, error output)

Flow

In Java IO, flow is a core concept. A flow is conceptually a continuous data stream. You can either read data from the stream or write data to it. A stream is associated with a data source or the medium in which the data flows. In Java IO, a stream can be either a byte stream (read and write in bytes) or a character stream (read and write in characters).

A program like InputStream, OutputStream, Reader and Writer requires InputStream or Reader to read data from the data source and OutputStream or Writer to write the data to the target medium. The following figure illustrates this:

InputStream and Reader are associated with the data source, and OutputStream and writer are associated with the target media.

The uses and characteristics of Java IO

Java IO contains many subclasses of InputStream, OutputStream, Reader, and Writer. The reason for this design is to make each class responsible for different functions. This is why there are so many different classes in the IO package. The various uses are summarized as follows:

File access network access memory cache access thread internal communication (pipe) buffer filtering parsing read-write text (Readers / Writers) read-write basic type data (long, int etc.) Read and write object

After reading through the source code of the Java IO class, it is easy to understand these uses. These uses more or less make it easier for us to understand that different classes are used for different business scenarios.

The Java IO class overview table has discussed data sources, target media, input, output, and various Java IO classes for different purposes, followed by a table of most Java IO classes divided by input, output, byte or character-based, and other specific purposes such as buffering, parsing, and so on.

What is a Java IO stream

A Java IO stream is a data stream that can be read from or written to. As mentioned earlier in this series of tutorials, circulation is often associated with data sources, data destinations, such as files, networks, and so on.

Unlike an array, a stream cannot read or write data through an index. In a stream, you can't read data back and forth like an array, unless you use RandomAccessFile to process files. A stream is just a continuous data stream.

Some implementations like PushbackInputStream streams allow you to push data back into the stream for re-reading. However, you can only push a limited amount of data back into the stream, and you can't read the data at will like an array. The data in the stream can only be accessed sequentially.

Java IO streams are usually byte-or character-based. Byte streams are usually named after "stream", such as InputStream and OutputStream. Except that DataInputStream and DataOutputStream can also read and write values of types int, long, float and double, other streams can only read or write one raw byte in an operation time.

Character circulation is often named "Reader" or "Writer". Character streams can read and write characters (such as Latin1 or Unicode characters). You can browse Java Readers and Writers for more information about character stream input and output.

InputStream

The java.io.InputStream class is the base class for all Java IO input streams. If you are developing a component that reads data from a stream, try developing it with InputStream instead of any of its subclasses (such as FileInputStream). Doing so makes your code compatible with any type of input stream rather than a certain type.

Combined flow

You can integrate streams for more advanced input and output operations. For example, it is slow to read one byte at a time, so you can read a large chunk of data from disk at a time, and then get bytes from the data blocks you read. To achieve buffering, you can wrap the InputStream in BufferedInputStream.

Code example InputStream input = new BufferedInputStream (new FileInputStream ("c:\ data\ input-file.txt"))

Buffering can also be applied to OutputStream. You can write large chunks of data to disk (or corresponding streams) in batches, which is implemented by BufferedOutputStream.

Buffering is just one of the effects achieved through stream integration. You can wrap the InputStream in PushbackInputStream, and then push the read data back into the stream to read again, which is sometimes convenient during parsing. Alternatively, you can integrate two InputStream into one SequenceInputStream.

More advanced operations can be achieved by integrating different streams into one chain. By writing a class that wraps a standard stream, you can achieve the effects and filters you want.

IO file

In Java applications, files are a common data source or medium for storing data. So this section will give a brief overview of the use of files in Java. This article will not explain every technical detail, but will provide you with some necessary knowledge about the methods of file access. In later articles, these methods or classes will be described in more detail, including method examples, and so on.

Read files through Java IO

If you need to read a file between different ends, you can choose to use FileInputStream or FileReader depending on whether the file is a binary file or a text file. These two classes allow you to read one byte or character at a time from the beginning of the file to the end of the file, or to write the read bytes to a byte array or character array. You don't have to read the whole file at once. Instead, you can read the bytes and characters in the file sequentially.

If you need to jump to read some parts of the file, you can use RandomAccessFile.

Write files through Java IO

If you need to write files between different ends, you can choose FileOutputStream or FileWriter depending on whether the data you want to write is binary data or character data. You can write one byte or character at a time to a file, or you can write an array of bytes or character data directly. Data is stored in the file in the order in which it is written.

Random access to files through Java IO

As I mentioned, you can access files randomly through RandomAccessFile.

Random access does not mean that you can read and write in a truly random location, it just means that you can skip parts of the file and support reading and writing at the same time, without requiring a specific access order. This allows RandomAccessFile to overwrite parts of a file, append content to its end, or delete some of its contents, but it can also start reading files from anywhere in the file.

Here are some specific examples:

@ Test / / file stream example, open the input stream of one file, read to a byte array, and then write to another file's output stream public void test1 () {try {FileInputStream fileInputStream = new FileInputStream ("a.txt"); FileOutputStream fileOutputStream = new FileOutputStream (new File ("b.txt")); byte [] buffer = new byte [128] While (fileInputStream.read (buffer)! =-1) {fileOutputStream.write (buffer);} / Random read and write. Read or write RandomAccessFile randomAccessFile = new RandomAccessFile (new File ("c.txt"), "rw") by mode parameter;} catch (FileNotFoundException e) {e.printStackTrace () } catch (IOException e) {e.printStackTrace ();}} character stream and byte stream

Java IO's Reader and Writer are very similar to InputStream and OutputStream except that they are character-based. They are used to read and write text. InputStream and OutputStream are byte-based, remember?

The Reader Reader class is the base class for all Reader in Java IO. Subclasses include BufferedReader,PushbackReader,InputStreamReader,StringReader and other Reader.

The Writer Writer class is the base class for all Writer in Java IO. Subcategories include BufferedWriter and PrintWriter, and so on.

This is a simple example of Java IO Reader:

Reader reader = new FileReader ("c:\\ data\\ myfile.txt"); int data = reader.read (); while (data! =-1) {char dataChar = (char) data; data = reader.read ();}

You usually use subclasses of Reader instead of using Reader directly. Subclasses of Reader include InputStreamReader,CharArrayReader,FileReader and so on. You can view the Java IO overview and browse the complete Reader table.

Integrate Reader and InputStream

A Reader can be combined with an InputStream. If you have an InputStream input stream and want to read characters from it, you can wrap the InputStream in InputStreamReader. Pass InputStream to the constructor of InputStreamReader:

Reader reader = new InputStreamReader (inputStream)

The decoding method can be specified in the constructor.

Writer

The Writer class is the base class for all Writer in Java IO. Subcategories include BufferedWriter and PrintWriter, and so on. This is an example of Java IO Writer:

Writer writer = new FileWriter ("c:\\ data\\ file-output.txt"); writer.write ("Hello World Writer"); writer.close ()

Again, you'd better use a subclass of Writer instead of using Writer directly, because the implementation of the subclass is more explicit and more expressive of your intentions. Common subcategories include OutputStreamWriter,CharArrayWriter,FileWriter and so on. The write (int c) method of Writer writes the lower 16 bits of the incoming parameters to the Writer, ignoring the high 16 bits.

Integrate Writer and OutputStream

Like Reader and InputStream, a Writer can be combined with an OutputStream. Wrap the OutputStream in OutputStreamWriter, and all characters written to OutputStreamWriter will be passed to OutputStream. This is an example of OutputStreamWriter:

Writer writer = new OutputStreamWriter (outputStream); IO pipe

Pipes in Java IO provide the ability for two threads running in the same JVM to communicate. So pipes can also be used as data sources and target media.

You cannot use pipes to communicate with threads in different JVM (different processes). Conceptually, pipes in Java are different from pipes in Unix/Linux systems. In Unix/Linux, two processes running in different address spaces can communicate through pipes. In Java, the two sides of communication should be different threads running in the same process.

Create pipes through Java IO

Pipes can be created through PipedOutputStream and PipedInputStream in Java IO. A PipedInputStream stream should be associated with a PipedOutputStream stream. Data written by one thread through the PipedOutputStream can be read by another thread through the associated PipedInputStream.

Java IO pipe example this is a simple example of how to associate PipedInputStream with PipedOutputStream:

/ / use pipes to complete point-to-point data transfer between two threads @ Test public void test2 () throws IOException {PipedInputStream pipedInputStream = new PipedInputStream (); PipedOutputStream pipedOutputStream = new PipedOutputStream (pipedInputStream); new Thread (new Runnable () {@ Override public void run () {try {pipedOutputStream.write ("hello input" .getBytes () PipedOutputStream.close ();} catch (IOException e) {e.printStackTrace ();}) .start () New Thread (new Runnable () {@ Override public void run () {try {byte [] arr = new byte [128]; while (pipedInputStream.read (arr)! =-1) {System.out.println (Arrays.toString (arr) } pipedInputStream.close ();} catch (IOException e) {e.printStackTrace ();}) .start ()

Pipes and threads remember that when using two associated pipe flows, be sure to assign them to different threads. Calls to the read () method and the write () method cause flow blocking, which means that if you try to read and write in the same thread at the same time, it may lead to thread deadlock.

In addition to pipes, there are many ways to communicate between different threads in an JVM. In fact, in most cases, threads pass complete object information rather than raw byte data. However, if you need to pass bytes of data between threads, Java IO's pipeline is a good choice.

Java IO: network

The content of the network in Java is more or less beyond the scope of Java IO. More about Java network is discussed in my Java network tutorial. But since the network is a common data source and data flow destination, and because you use Java IO's API to communicate over a network connection, this article will briefly cover network applications.

When a network connection is established between the two processes, they communicate in the same way as operating files: reading data using InputStream and writing data using OutputStream. In other words, the Java network API is used to establish network connections between different processes, while Java IO is used to exchange data between processes after the connection is established.

Basically it means that if you have a code that can write some data to a file, then that data can also be easily written to a network connection. All you need to do is write data in the code using OutputStream instead of FileOutputStream. Because FileOutputStream is a subclass of OuputStream, there is no problem with doing so.

/ / read byte streams from the network can also be read directly using OutputStreampublic void test3 () {/ / read the output stream of the network process OutputStream outputStream = new OutputStream () {@ Override public void write (int b) throws IOException {}};} public void process (OutputStream ouput) throws IOException {/ / process network information / / do something with the OutputStream} byte and character array

Read an array from InputStream or Reader

Write arrays from OutputStream or Writer

Byte and character arrays are commonly used in java to temporarily store data in applications. These arrays are the usual data read sources or write destinations. If you need to read a lot of the contents of a file while the program is running, you can also load a file into an array.

In the previous example, character arrays or byte arrays are temporary storage spaces for caching data, but they can also be used as data sources or write destinations. For example:

/ / the role of character array and byte array in the io process public void test4 () {/ / arr and brr are used as data sources char [] arr = {'a'axiomagronomy, respectively; CharArrayReader charArrayReader = new CharArrayReader (arr); byte [] brr = {1meme2parentin 5}; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream (brr);} System.in, System.out, System.err

System.in, System.out and System.err are also common data sources and data flow destinations. Probably the most frequently used is to print the output to the console using System.out in the console program.

These three streams are initialized by the Java runtime when JVM starts, so you don't need to initialize them (although you can replace them at run time).

System.inSystem.in is a typical InputStream stream that connects console programs to keyboard input. Usually, System.in is not very common when data is passed to command-line Java programs through command-line arguments or configuration files. The graphical interface program transfers parameters to the program through the interface, which is a separate Java IO input mechanism. System.outSystem.out is a PrintStream stream. System.out usually outputs the data you write to it to the console. System.out is usually used only on console programs like command-line tools. System.out is also often used to print debugging information for a program (although it may not be the best way to get debugging information for a program). System.errSystem.err is a PrintStream stream. System.err works like System.out, but it is more used to print error text. Some Eclipse-like programs, in order to make the error message more visible, will output the error message to the console in red text via System.err.

Simple example of System.out and System.err: this is a simple example of a combination of System.out and System.err:

/ / Test System.in, System.out, System.err public static void main (String [] args) {int in = new Scanner (System.in) .nextInt (); System.out.println (in); System.out.println ("out"); System.err.println ("err") / / enter 10, and the result is / / err (red) / / 10 Buffered / out} character stream Buffered and Filter

BufferedReader provides buffers for character input streams, which can speed up a lot of IO processing. You can read large chunks of data at a time without having to read one byte at a time from the network or disk. Buffering usually makes IO much faster, especially when accessing large amounts of disk data.

The main difference between BufferedReader and BufferedInputStream is that BufferedReader operates on characters, while BufferedInputStream operates on raw bytes. You just need to wrap the Reader in BufferedReader to add a buffer for Reader (the default buffer size is 8192 bytes, or 8KB). The code is as follows:

Reader input = new BufferedReader (new FileReader ("c:\\ data\\ input-file.txt")

You can also specify the buffer size by passing the second parameter of the constructor, as follows:

Reader input = new BufferedReader (new FileReader ("c:\\ data\\ input-file.txt"), 8 * 1024)

This example sets the buffer for 8KB. It is best to set the buffer size to an integer multiple of 1024 bytes so that the disk of the built-in buffer can be used more efficiently.

Except for the ability to provide buffers for input streams, BufferedReader is basically similar to Reader in other aspects. BufferedReader also has an additional readLine () method that makes it easy to read an entire line of characters at once.

BufferedWriter

Like BufferedReader, BufferedWriter can provide buffers for the output stream. You can construct a BufferedWriter that uses the default size buffer, with the following code:

Writer writer = new BufferedWriter (new FileWriter ("c:\\ data\\ output-file.txt")

You can also set the buffer size manually as follows:

Writer writer = new BufferedWriter (new FileWriter ("c:\\ data\\ output-file.txt"), 8 * 1024)

To make better use of disks with built-in buffers, it is also recommended that the buffer size be set to an integer multiple of 1024. Except that it can provide buffers for the output stream, BufferedWriter is basically similar to Writer in other aspects. Similarly, BufferedWriter also provides a writeLine () method that writes a line of characters to the underlying character output stream.

It is worth noting that you need the manual flush () method to ensure that the data written to this output stream is actually written to disk or to the network.

FilterReader

Like FilterInputStream, FilterReader is the base class for implementing custom filtering of input character streams, basically simply overriding all the methods in Reader.

As far as I'm concerned, I don't see any obvious use for this category. I don't see anything new or modified to Reader by FilterReader except that the constructor takes a Reader variable as an argument. If you choose to inherit custom classes implemented by FilterReader, you can also inherit directly from Reader to avoid additional class hierarchies.

Thank you for your reading, the above is the content of "what is the Java IO stream?" after the study of this article, I believe you have a deeper understanding of what the Java IO stream is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Development

Wechat

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

12
Report