JAVA input and output

Source: Internet
Author: User
Tags object serialization
JAVA input and output
Category: Default topic
The JAVA input and output functions are very powerful and flexible. What is lacking in the US is that the input and output code is not very concise, Because you often need to wrap many different objects. In Java class libraries, the I/O part of the content is very large, because it involves a wide range of fields: standard input and output, file operations, network data streams, string streams, object stream, zip file stream .... the purpose of this article is to give a brief introduction.
Stream is a very visual concept. When the program needs to read data, it will open a stream to the data source, which can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination. At this time, you can imagine that the data is like a "stream" in it, such:
 
 
In Java, streams are divided into two types: byte streams and merge streams, which are represented by four abstract classes respectively (each type of stream includes two types of input and output, so there are four in total ): inputstream, outputstream, reader, and writer. In Java, other diverse stream types are derived from them.
 
Among them, inputstream and outputstream already exist in earlier Java versions. They are based on byte streams, while reader and writer based on bytes streams are later added as supplements. The above level chart is a basic level system in the Java class library.
In these four abstract classes, inputstream and reader define the same interface:
Int read ()
Int read (char cbuf [])
Int read (char cbuf [], int offset, int length)
The same is true for outputstream and Writer:
Int write (int c)
Int write (char cbuf [])
Int write (char cbuf [], int offset, int length)
These six methods are the most basic. Read () and write () read a byte or a byte array through method overloading.
More flexible and variable functions are extended by their subclasses. After learning about the basic hierarchy of JAVA input and output, this article will give you some examples that can be used repeatedly in the future. The details of all sub-classes and their functions are not discussed in detail.
Import java. Io .*;
Public class iostreamdemo {

Public void samples () throws ioexception {
// 1. This is to read a row of data from the keyboard and return a string
Bufferedreader stdin = new bufferedreader (New inputstreamreader (system. In ));
System. Out. Print ("enter a line :");
System. Out. println (stdin. Readline ());
// 2. This is to read data row by row from the file
Bufferedreader in = new bufferedreader (New filereader ("iostreamdemo. Java "));
String S, S2 = new string ();
While (S = in. Readline ())! = NULL)
S2 + = S + "/N ";
In. Close ();
// 3. This is to read bytes one by one from a string
Stringreader in1 = new stringreader (S2 );
Int C;
While (C = in1.read ())! =-1)
System. Out. Print (char) C );
// 4. This is to write a string into 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, we need to explain the following points:
1. bufferedreader is a sub-class of reader. It can buffer data and avoid reading information from physical devices frequently. It has the following constructor:
2. bufferedreader (Reader in)
Bufferedreader (Reader in, int sz)
The SZ here specifies the buffer size.
The basic method is as follows:
Void close () // close the stream

Void mark (INT readaheadlimit) // mark the current location

Boolean marksupported () // whether tag is supported

Int read () // basic method inherited from Reader

Int read (char [] cbuf, int off, int Len) // basic method inherited from Reader

String Readline () // read a line of content and return it as a string

Boolean ready () // determines whether the stream is ready for reading.

Void reset () // reset to the nearest mark

Long SKIP (long n) // skip reading a specified number of characters
2. inputstreamreader is a bridge between inputstream and reader. Because system. In is a byte stream, it needs to be packaged and then changed to a bytes stream for bufferedreader.
3. printwriter out1 = new printwriter (New bufferedwriter (New filewriter ("iodemo. Out ")));
This statement represents a feature of the JAVA input/output system. for a specific purpose, several layers need to be packaged. First, the output destination is the file iodemo. therefore, filewriter is encapsulated at the innermost layer to create an output file stream. Next, we want this stream to be buffered. Therefore, bufferedwriter is used to package it for the purpose. Finally, we need to format the output result, so we put the printwriter package in the outermost layer.
Java provides such a function to switch the standard input/output stream. That is to say, we can set another stream as a standard input or output stream. 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 );
}
}
The static method of Java. Lang. System
Static void setin (inputstream in)
Static void setout (printstream out)
It is convenient to redefine the standard input/output stream. For example, there are many results in a program, and sometimes the results may even be displayed on pages, which makes it difficult to view the results, you can define a standard output stream as a file stream. After the program runs, you can open the corresponding file to view the results, which is much more intuitive.
Java streams have another important purpose, that is, serialization of objects using object streams. The following describes the problem.
When a program runs, the variable data is stored in the memory. Once the program ends, the data will not be saved. One solution is to write the data to a file, java provides a mechanism to write the objects in the program to a file, and then read the objects from the file and recreate them. This is the so-called Object serialization java. It is mainly used for RMI (Remote Method Invocation) and Java Bean. However, it is also a useful technology in common applications.
All objects that require Object serialization must first implement the serializable interface. The following is an example:
Import java. Io .*;
Import java. util .*;
Public class logon implements serializable {

Private 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 =" + );
Objectoutputstream o = new objectoutputstream (New fileoutputstream ("Logon. Out "));
O. writeobject ();
O. Close ();
Int seconds = 5;
Long T = system. currenttimemillis () + secondds * 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 =" + );
}
}
Logon is a class that records logon information, including the user name and password. First, it implements the interface serializable, which indicates that it can be serialized. Then in the main method, objectoutputstream o = new objectoutputstream (New fileoutputstream ("logon. "Out"). Create an object output stream to wrap a file stream, indicating that the object serialization destination is the file logon. out. Then, use the writeobject method to start writing. Objectinputstream in = new objectinputstream (New fileinputstream ("logon. out "); creates an object input stream to use the file stream logon. the out parameter is used to call the readobject method.
It should be noted that the magic of Object serialization is that it creates an object network and includes all the objects referenced in the objects to be serialized and writes them to the file, even more importantly, if you serialize several objects at a time, the same content will be shared and written to them. This is indeed a very good mechanism. It can be used for deep copy.
The keyword transient indicates that the current content will not be serialized. For example, the password in the example needs to be kept confidential, so it is not written into the file.
I will briefly introduce the input and output functions of Java. The purpose of this article is just to provide a good start and hope to give you a basic understanding of the JAVA input and output stream.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.