The input and output capabilities of the Java language are very powerful and flexible, and the drawback is that the code that looks like input and output is not very concise, because you often need to wrap many different objects. In the Java class Library, the IO part of the content is very large, because it involves a wide range of areas: standard input and output, file operations, network data flow, string flow, object flow, zip file flow .... The purpose of this article is to give you a brief introduction.
Flow is a very graphic concept, when the program needs to read data, it will open a stream to the data source, this data source can be file, memory, or network connection. Similarly, when a program needs to write data, it opens a stream to the destination. At this point you can imagine that the data seems to be moving in this way, as in the following figure:
There are two kinds of streams in Java, one is the byte stream, the other is a stream of characters, which is represented by four abstract classes (each stream includes input and output, so altogether four): Inputstream,outputstream,reader,writer. Other streams of varying variations in Java are derived from them:
In which InputStream and OutputStream already existed in earlier versions of Java, they were based on byte streams, and the reader and writer based on the character stream were later added as supplements. The above hierarchy diagram is a basic hierarchical system in Java class libraries.
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 is true of OutputStream and writer:
int write (int c)
int write (char cbuf[])
int write (char cbuf[], int offset, int length)
These six methods are most basic, read () and write () are read and written to a byte, or an array of bytes, by the overload of the method.
More flexible functions are expanded by their subclasses. After knowing the basic hierarchy of Java input and output, this article here wants to give you some examples that can be reused in the future, and the details of all subclasses and their functions are not discussed in detail.
Import java.io.* public class Iostreamdemo {public void samples () throws IOException {//1. This is a line of data that is read from the keyboard and returns the A string BufferedReader stdin =new BufferedReader (New InputStreamReader (system.in)); System.out.print ("Enter A L INE: "); System.out.println (Stdin.readline ());//2. This is a line-by-row reading of data from a file BufferedReader in = new BufferedReader (New FileReader ("Iostreamdemo.java")); String s, s2 = new S Tring () while ((s = in.readline ())!= null) s2 + = + "\ n"; In.close (); This is read from one string to the byte StringReader in1 = new StringReader (s2); int c; while ((c = in1.read ())!=-1) S Ystem.out.print ((char) c);//4. This is to write a string to the file try {bufferedreader in2 = new BufferedReader (new StringReader (S2)); PrintWriter out1 = new PrintWriter (New BufferedWriter ("Iodemo.out")); int linecount = 1; while ((s = In2.rea Dline ())!= 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 a buffering effect, avoiding the frequent reading of 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.
It's basic methods:
void Close ()//Turn off flow
void mark (int readaheadlimit)//Mark current Position
boolean marksupported ()//whether to support Mark
int read ()// The basic method of inheriting from reader
int read (char[] cbuf, int off, int len)////inherits from Reader's Basic method
string ReadLine ()//reads a line and returns as a string
Boolean Ready ()//To determine if the stream is ready to read.
void Reset ()//reset to the nearest token
long Skip (long N)//skip a specified number of character reads
2. InputStreamReader is a bridge between InputStream and reader, because System.in is a byte stream, it needs to be packaged and then transformed into a character streams supply bufferedreader use.
3. PrintWriter out1 = new PrintWriter (new BufferedWriter) (New FileWriter ("Iodemo.out"));
This statement embodies a Java input and output system of a feature, in order to achieve a certain purpose, need to wrap several layers. First of all Output destination is file Iodemo.out, so the most inner packaging is filewriter, create an output file stream, Next, we hope that this stream is buffered, so use bufferedwriter to wrap it to achieve the goal, finally, we need to format the output results, so we will PrintWriter Wrap in the outermost layer.
Java provides the ability to turn a standard input-output stream, which means that 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 {
Prin Tstream console = System.out
bufferedinputstream in = new Bufferedinputstream (New FileInputStream (" Redirecting.java "));
PrintStream out = new PrintStream (New Bufferedoutputstream (" FileOutputStream " ));
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 here
static void Setin (InputStream in)
static void SetOut (PrintStream out)
Provides a way to redefine the standard input and output stream, this is very convenient, such as a program has a lot of results, sometimes even to turn the page to display, so it is not easy to view the results, this is you can define the standard output stream as a file flow, the program after running the corresponding file to see the results, it is intuitive a lot.
Another important use of Java streams is the use of object streams to serialize objects. The following will begin to introduce the issues in this regard.
When a program is running, the variable data is stored in memory, 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 objects in the program to the file, and then read the object from the file to re-establish. This is the so-called object serialization Java introduced it is primarily for RMI (Remote method invocation) and Java beans, but in peacetime applications, it is also a useful technology.
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 = new D
Ate (); private string username private transient string password Logon (string name, string pwd) { Username = name; password = pwd} public string toString () {string pwd = (password = n ull)? "(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 ObjectOutput Stream (New FileOutputStream ("Logon.out")); O.writeobject (a); O.close (); int seconds = 5; lon G T = System.currenttimemillis () + seconds * 1000 while (System.currenttimemillis () < T); objectinputst Ream 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);}}
Class logon is a class that records logon information, including user names and passwords. 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")), a new object output stream wraps a file stream, The destination that represents the serialization of an object is a file logon.out. Then use the method writeobject to begin writing. It's also very simple when you want to restore objectinputstream in = new ObjectInputStream (New FileInputStream ("Logon.out")) A new object input stream is logon.out as a parameter, then the ReadObject method is invoked.
To be clear, one of the wonders of object serialization is that it creates a web of objects that contain references to objects held in the object currently being serialized and are written to the file together, even more wonderfully, if you serialize several objects at once, the same content will be written to share. This is indeed a very good mechanism. It can be used to implement deep copies.
The keyword transient here indicates 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.
The Java input and output function, on the shallow introduction to here, the purpose of this article is to open a good head, hoping to let you have a basic knowledge of the Java input and output stream.
Original Address (http://www.yesky.com/88/1700588.shtml)