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

The concept of input and output streams of Java

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

Share

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

This article mainly explains "the concept of input and output stream of Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the concept of input and output stream of Java.

The input and output function of Java language is very powerful and flexible, but the only drawback is that the input and output code is not very concise, because you often need to wrap a lot of different objects. In the Java class library, the content of the IO part is very large, because it covers a wide range of fields: standard input and output, file manipulation, network data flow, string stream, object stream, zip file stream. The purpose of this article is to give you a brief introduction.

Stream is a very vivid concept. When a program needs to read data, it opens a stream to a data source, which can be a file, memory, or a network connection. Similarly, when the program needs to write data, it opens a stream to the destination. At this point, you can imagine that the data is "flowing" in it.

There are two types of streams in Java, one is a byte stream, and the other is a character stream, represented by four abstract classes (each stream includes input and output, so there are four): InputStream,OutputStream,Reader,Writer. Other varied flows in Java are derived from them.

InputStream and OutputStream have existed in earlier versions of Java, and they are based on byte streams, while character stream-based Reader and Writer were later added as a supplement. The above hierarchy diagram is a basic hierarchy in the Java class library.

In these four abstract classes, InputStream and Reader define exactly the same interface:

Int read () int read (char cbuf []) int read (char cbuf [], int offset, int length)

The same goes for OutputStream and Writer:

Int write (int c) int write (char cbuf []) int write (char cbuf [], int offset, int length)

All six methods are basic. Read () and write () read and write a byte, or a byte array, through the overloading of the method.

More flexible functions are extended by their subclasses. After knowing the basic hierarchical structure of Java input and output, this article would like to give you some examples that can be applied repeatedly in the future. The details and functions of all subclasses are not discussed in detail.

Import java.io.*; public class IOStreamDemo {public void samples () throws IOException {/ / 1. This reads a line of data from the keyboard and returns the string BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); System.out.print ("Enter a line:"); System.out.println (stdin.readLine ()); / / 2. This reads BufferedReader in = new BufferedReader (new FileReader ("IOStreamDemo.java")) line by line from the file; String s, S2 = new String (); while ((s = in.readLine ())! = null) S2 + = s + "\ n"; in.close (); / / 3. This reads the bytes StringReader in1 = new StringReader (S2); int c; while ((c = in1.read ())! =-1) System.out.print ((char) c) one by one from a string. This is to write a string to the file try {BufferedReader in2 = new BufferedReader (new StringReader (S2)); PrintWriter out1 = new PrintWriter (new BufferedWriter (new FileWriter ("IODemo.out"); int lineCount = 1 While ((s = in2.readLine ())! = null) out1.println (lineCount++ + ":" + s); out1.close ();} catch (EOFException e) {System.err.println ("End of stream") }

For the above example, the following points need to be explained:

1. BufferedReader is a subclass of Reader, which has the function of buffering and avoids frequently reading information from physical devices. It has the following two constructors:

BufferedReader (Reader in)

BufferedReader (Reader in, int sz)

The sz here is the size of the specified buffer.

Its basic method:

Void close () / / close stream void mark (int readAheadLimit) / / tag current location boolean markSupported () / / support tag int read () / / basic methods inherited from Reader int read (char [] cbuf, int off Int len) / / inherits from Reader's basic method String readLine () / / reads a line and returns boolean ready () / / as a string to determine whether the stream is ready to be read void reset () / / reset to the nearest tag long skip (long n) / / skip the specified number of characters to read

2. InputStreamReader is the bridge between InputStream and Reader. Because System.in is a byte stream, it needs to be wrapped into a character stream for BufferedReader to use.

3. PrintWriter out1 = new PrintWriter (new BufferedWriter (new FileWriter ("IODemo.out"))

This sentence reflects a feature of the Java input and output system, which requires several layers of packaging to achieve a certain purpose. First of all, the output destination is the file IODemo.out, so the innermost layer wraps FileWriter, and creates an output file stream. Next, we want the stream to be buffered, so we wrap it in BufferedWriter to achieve our goal. *, we need to format the output, so we wrap PrintWriter in the outermost layer.

Java provides the ability to redirect standard input and output streams, that is, we can set some other stream as a standard input or output stream, as shown in the following example:

Import java.io.*; public class Redirecting {public static void main (String [] args) throws IOException {PrintStream console = System.out; BufferedInputStream in = new BufferedInputStream (new FileInputStream ("Redirecting.java")); PrintStream out = new PrintStream (new BufferedOutputStream (new FileOutputStream ("test.out"); System.setIn (in); System.setOut (out) BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); String s; while ((s = br.readLine ())! = null) System.out.println (s); out.close (); System.setOut (console);}}

Here is the static method of java.lang.System:

Static void setIn (InputStream in) static void setOut (PrintStream out)

Provide a way to redefine the standard input and output stream, this is very convenient, for example, a program has a lot of results, sometimes even to turn the page to display, so it is not easy to see the results, this is that you can define the standard output stream as a file stream, after the program runs, it is much more intuitive to open the corresponding file to watch the results.

Another important use of Java streams is to serialize objects using object streams. We will begin to introduce this issue below.

When a program is running, the variable data is saved in memory, and once the program is finished, the data will not be saved. One solution is to write the data to the file, and Java provides a mechanism that can write the objects in the program to the file, and then read the objects from the file to re-establish. This is the so-called object serialization Java introduced mainly for RMI (Remote Method Invocation) and Java Bean, but it is also a very useful technology in everyday applications.

All objects that need to implement object serialization must first implement the Serializable interface. Let's look at an example:

Import java.io.*; import java.util.*; public class Logon implements Serializable {private Date date = new Date (); private String username; private transient String password; Logon (String name, String pwd) {username = name; password = pwd;} public String toString () {String pwd = (password = = null)? "(nhand a)": password Return "logon info:\ n" + "username:" + username + "\ ndate:" + date + "\ npassword:" + pwd;} public static void main (String [] args) throws IOException, ClassNotFoundException {Logon a = new Logon ("Morgan", "morgan83"); System.out.println ("logon a =" + a) ObjectOutputStream o = new ObjectOutputStream (new FileOutputStream ("Logon.out")); o.writeObject (a); o.close (); int seconds = 5; long t = System.currentTimeMillis () + seconds * 1000; while (System.currentTimeMillis () < t); ObjectInputStream in = new ObjectInputStream (new FileInputStream ("Logon.out")) System.out.println ("Recovering object at" + new Date ()); a = (Logon) in.readObject (); System.out.println ("logon a =" + a);}}

The class Logon is a class that records login information, including user names and passwords. First it implements the interface Serializable, which indicates that it can be serialized. Then ObjectOutputStream o = new ObjectOutputStream (new FileOutputStream ("Logon.out")) in the main method; create a new object output stream that wraps a file stream, indicating that the destination of the object serialization is the file Logon.out. Then start writing with the method writeObject. When you want to restore, it is also very simple ObjectInputStream in = new ObjectInputStream (new FileInputStream ("Logon.out")); create a new object input stream with the file stream Logon.out as the parameter, and then call the readObject method.

It is important to note that the magic of object serialization is that it establishes an object network that contains all the references held in the objects to be serialized and writes them to a file, and even more wonderfully, if you serialize several objects at a time, the same content in them will be shared. This is indeed a very good mechanism. It can be used to make deep copies.

The keyword transient here means that the current content will not be serialized, such as the password in the example, which needs to be kept secret, so it is not written to the file.

At this point, I believe you have a deeper understanding of "the concept of Java input and output stream". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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