Talking about Java input and output flow

xiaoxiao2021-03-06  124

Talking about the Java's input and output flow original: Morgan83 Source: Flying Technology Network April 1, 2003

The input and output function of the Java language is very powerful and flexible. It is not very concise code that looks into the output, because you often need to pack many different objects. In the Java class library, the content of the IO section is very large, because it involves a wide range: standard input and output, file operation, data stream on the network, string stream, target flow, zip file stream ... The purpose of this article is to make a brief introduction to everyone.

The stream is a very image of the concept. When the program needs to read the data, the stream to the data source is turned on, which can be file, memory, or network connection. Similarly, when the program needs to write data, a stream that is noted to destination is turned on. At this time, you can imagine that the data is like "stream", as shown below:

The stream in Java is two, one is byte stream, the other is a character stream, which is represented by four abstractions (each stream includes two types of inputs and outputs): InputStream, OutputStream , Reader, Writer. There are many other variations in Java, which are derived from them:

In this, InputStream and OutputStream already exist in early Java versions, they are based on byte streaming, while characteristic-based Reader and Writer are later joined as supplements. The above level map is a basic hierarchy in the Java class library. If you are interested in seeing more, you can get more information to the Sun Home page.

In these four abstractions, InputStream and Reader define the exact same interface:

INT read () int in (char cbuf []) int in (char cbuf [], int offset, int ingth)

The same is true of OutputStream and Writer:

Int Write (int C) Int Write (Char Cbuf []) int Write (Char Cbuf [], int offset, int LENGTH)

These six ways are the most basic, read () and write () read one byte or one byte array through the overload of the method.

More flexible and variable functions are expanded by their subclasses. After knowing the basic hierarchy of Java input and output, this article wants to give you some reassessment examples, and discussed in detail for all subclasses.

Import java.io. *;

Public class ostreamdemo {public void samples () throws oException {

// 1. This is a row of data from the keyboard, returning is a string bufferedreader stdin = new buffredreader (IStem.in); system.out.print ("Enter a line:"); system. Out.println (stdin.readline ());

// 2. This is an enlarged data from the file.

BufferedReader in = new bufferedreader ("iostreamDemo.java); string s, s2 = new string (); while ((s = in.readline ())! = Null) S2 = s " / N ", In .close (); // 3. This is an incoming byte stringReader in1 = New stringReader (S2); INT C; WHILE (((c = in1.read ())! = - 1) System.out.print (CHAR) C);

// 4. This is written to write a string Try {buffredreader in2 = new bufferedreader (new stringReader (new stringReader (new bufferedwriter))); int Filewriter 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, you need to explain the following:

1. BufferedReader is a subclass of Reader, which has buffering effects to avoid frequent frequent reading information from the physical device. It has the following two constructor:

BufferedReader (Reader in) BufferedReader (Reader In, Int Sz)

The SZ here is the size of the specified buffer.

Its basic method:

Void Close () // Close the flow void mark (int tentaheadlimit) / / mark the current location Boolean Marksupported () // Whether to support the Int Read () // Inherited Basic Method Int Read (Char [] CBUF, INT OFF , int LEN) // Inherits the basic method of Reader string readline () // reads a line of content and returns Boolean Ready () // in a string, whether the stream is ready to read. Void Reset () // Reset to a nearest tag long Skip (long n) // skip the specified number of characters read

2. InputStreamReader is the bridge between InputStream and Reader, because system.in is a byte stream, it is necessary to use it to package the bufferedReader to use it. 3. Printwriter out1 = new printwriter (New Filewriter ("IODEMO.OUT"))

This sentence reflects a feature of the Java input and output system. In order to achieve a purpose, you need to pack several layers. First, the output destination is the file odemo.out, so the innermost package is filewriter, establish an output file stream, then we hope this stream is buffered, so use bufferedWriter to pack it to achieve the purpose, and finally, we It is necessary to format the output result, so put the PrintWriter package in the outermost layer.

Java provides such a function to turn the standard input output stream, that is, we can use some other ciros to input or output streams, see 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 Java.lang.system static method

Static void setin (InputStream in) static void setout (PrintStream Out)

It is very convenient to redefine the standard input and output streams, so that there is a lot of programs, sometimes even turn pages, so that you can view the results, this is you can define the standard output stream For a file stream, the program is turned on after running, and it is intuitive.

Java has another important purpose, which is to serve as an object flow to the object. Here will begin to introduce this problem.

When running in a program, the variable data is saved in memory. Once the program ends these data will not be saved, a solution is to write data into the file, and a mechanism is provided in Java. It can write objects in the program to the file, then read the object from the file to re-establish. This is the so-called object serialization in Java to introduce it mainly for RMI (Remote Method Invocation) and Java Beans, but it is also a useful technology in usual applications. All objects that require object serialization must first implement the serializable interface. Let's take a look at one 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)? "(N / a)": password; return "logon info: / n" "UserName:" username "/ n Date: " Date " / N Password: " 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 second divonds = 5; long t = System.currentTimeMillis () Seconds * 1000; While (System.currentt imeMillis ()

Keyword Transient Here, the current content will not be serialized, such as password in an example, requires confidentiality, so no file is written.

For Java's input and output function, it is shallow introduction to here. The purpose of this article is just to open a good head. I hope everyone has a basic understanding of Java input and output flows, more more comprehensive information in http: / /java.sun.com has an authoritative instructions.

转载请注明原文地址:https://www.9cbs.com/read-100798.html

New Post(0)