Java I/O Streams

Source: Internet
Author: User
Tags square root
Byte Streams

The program uses byte streams to input and output bytes (8-bit), all of which are inherited from InputStream and OutputStream.

The Java platform defines a lot of bytes for us, and we focus on the file byte stream, so we can better demonstrate that the other byte streams are not as different as they used to be, except for the constructors.

We have a case to start exploring the word throttling bar.

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;

public class Copybytes {public
    static void Main (string[] args) throws IOException {

        FileInputStream in = Null;
  fileoutputstream out = null;

        try {in
            = new FileInputStream ("Xanadu.txt");
            out = new FileOutputStream ("Outagain.txt");
            int C;

            while ((c = in.read ())!=-1) {
                out.write (c);
            }}
        finally {
            if (in!= null) {
                in.close ();
            }
            if (out!= null) {
                out.close ();
            }
    }}
}

But this copybytes program is inefficient because we have a lot of time to repeat this rotation (read a byte from the input stream, write a byte from the output stream), and we'll show you the workflow of this code:


When we want to remind you of a point here, we have to remember to turn it off when we don't need a stream to make sure we don't waste resources.

We do it in the finally, so we can safely turn off the stream if we make a mistake in time.

Copybytes looks like a normal program, but it actually represents a low level I/O that you should avoid. Because Xanadu.txt contains character data, the best approach is to use character streams. There are, of course, more complex streams of data types. Byte throttling We are generally used only for the most original I/O operations.
Character Streams

The Java platform uses Unicode encoding to store characters. Character stream I/O automatically converts this internal format to the local character set or from the local character set.

The character stream is as simple as the byte byte, and we don't have to focus on how to parse it into the local character set, and if we do need globalization, we can see the globalization module.

All the character stream classes inherit from reader and Writer, and of course we take a particular input output as an example, we choose to use file I/O: FileReader and FileWriter.

Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;

public class Copycharacters {public
    static void Main (string[] args) throws IOException {FileReader

        InputStream = null;
        FileWriter outputstream = null;

        try {
            InputStream = new FileReader ("Xanadu.txt");
            OutputStream = new FileWriter ("Characteroutput.txt");

            int C;
            while ((c = inputstream.read ())!=-1) {
                outputstream.write (c);
            }}
        finally {
            if (InputStream!= null ) {
                inputstream.close ();
            }
            if (OutputStream!= null) {
                outputstream.close ()}}}}
It is worth the time that we are all using variables of type int to accept, what is the difference between the byte stream and the character streams? Of course, when using a character stream, the int variable holds a character value in the last 16 bits; In a byte stream, the int variable holds a value in its last 8 bits.

We can also be a stream of characters as a byte of the proxy, character streams at the bottom of the stream using the word throttling for I/O operations, but added from the character to byte operations, InputStreamReader and OutputStreamWriter is the stream of bytes and character streams between the transformation of the bridge. line-oriented I/O

Usually the characters are not single, there is a common place is the row, may be "\ r \ n", also may be "\ r", and possibly the "\ n" operating system different from its line terminator.

Let's change the above case instead to use line-oriented I/O, and in order to do that we have to use BufferedReader and PrintWriter. These two classes have been, and we will be back to buffered I/O In-depth discussions with formatting, but now we focus on the line I/O they support.

Import Java.io.FileReader;
Import Java.io.FileWriter;
Import Java.io.BufferedReader;
Import Java.io.PrintWriter;
Import java.io.IOException;

public class Copylines {public
    static void Main (string[] args) throws IOException {BufferedReader

        InputStream = null;
        PrintWriter outputstream = null;

        try {
            InputStream = new BufferedReader (New FileReader ("Xanadu.txt"));
            OutputStream = new PrintWriter (New FileWriter ("Characteroutput.txt"));

            String l;
            while ((L = inputstream.readline ())!= null) {
                outputstream.println (l);
            }
        }} finally {
            if ( InputStream!= null) {
                inputstream.close ();
            }
            if (OutputStream!= null) {
                outputstream.close ()}}}}
Buffered Streams

Several cases so far have been the use of no buffered I/O, which means that each time we read and write requests are directly through the OS, this is inefficient, should be for each request is triggered disk operation, network, or some other operation. To reduce these costs, the Java platform implements the buffered I/O stream, buffered input streams reads from memory, and the local input API is invoked only when the buffer is empty, buffered output Streams writes data through the buffer, and the local output API is invoked only when the buffer is full.

A buffer-free stream can be converted into buffered by using a proxy for conversion.

For example:

InputStream = new BufferedReader (New FileReader ("Xanadu.txt"));
OutputStream = new BufferedWriter (New FileWriter ("Characteroutput.txt"));

There are four classes that are used to perform a proxy without buffering:

Bufferedinputstream and Bufferedoutputstream//create buffered byte streams 
BufferedReader and BufferedWriter// Create buffered character streams

There are times when we may require that data be written before the buffer is full, and we call this operation Flushing buffered Streams.

Some of the buffered output classes can support automatic refreshes by manipulating constructors, but when automatic refreshes are allowed, some events trigger a refresh operation, such as a PrintWriter object that allows refreshing to trigger a refresh when calling println or format.

Of course, we can also make a manual call to the Flush () method, which can be invoked in any output stream, but is not valid if it is not a buffer stream. Scanning and formatting

I/O programming sometimes needs to be translated into a human-like format, and the Java platform provides two classes to help us complete the operation scanner and formatting. Scanning

An object of type scanner can be used to decompose formatted input into tokens and to convert a single tokens based on its data type

By default, scanner is split with whitespace characters (whitespace, tab, and line terminator)

The following is a small case:

Import java.io.*;
Import Java.util.Scanner;

public class Scanxan {public
    static void Main (string[] args) throws IOException {

        Scanner s = null;

        try {
            s = new Scanner (new BufferedReader (New FileReader ("Xanadu.txt"));

            while (S.hasnext ()) {
                System.out.println (S.next ());
            }
        } finally {
            if (s!= null) {
                s.close (); c14/>}}}

What needs to be mentioned here is that we call Close () here, although scanner is not a stream, it indicates that you have completed its underlying stream.

When you want to use different delimiters, you should call the scanner Usedelimiter () method and pass the regular expression. Formatting

If the stream object is implemented as an instance of formatting, such as: PrintWriter (a character stream class), PrintStream (a Byte throttle Class)

It is worth mentioning that you should use PrintWriter to format the output instead of PrintStream except (System.out and System.err);

Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Provides two levels of formatting:

(1) Basic (print and println);

(2) formatted (format);

The print and println Methods

public class Root {public
    static void Main (string[] args) {
        int i = 2;
        Double R = math.sqrt (i);
        
        System.out.print ("The square root of");
        System.out.print (i);
        System.out.print ("is");
        System.out.print (r);
        System.out.println (".");

        i = 5;
        R = math.sqrt (i);
        System.out.println ("The square root of" + i + "is" + R + ".");
    }

The Format method

public class Root2 {public
    static void Main (string[] args) {
        int i = 2;
        Double R = math.sqrt (i);
        
        System.out.format ("The square root of%d is%f.%n", I, r);
    }
}
I/O from the Command line Data Streams

Data flow supports byte I/O base data Types (Boolean, char, Byte, short, int, long, float, double, and String) all implementations are dependent on the  datainput or DataOutput interface, but we're only going to talk about the most widely used implementation classes:  datainputstream and DataOutputStream.

	Static final String datafile = "InvoiceData";
	Static final double[] prices = {19.99, 9.99, 15.99, 3.99, 4.99};
	Although the price we should not use double should be for him just like the decimal cannot represent eleven-thirds samples cannot represent 0.1, but we use the static final int[] units = {12, 8, 13, 29, 50} to test the basic data type of I/O. Static final string[] Descs = {"Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "
	Java Key Chain "};
		public static void Main (string[] args) throws exception{out ();
	In ();  } * * It is noteworthy that Datastreams uses eofexception to determine whether to read the end of the file * All methods of implementing Datainput are using Eofexception to determine the ending rather than the return value * * */Public
	            static void in () throws FileNotFoundException, IOException {datainputstream in = new DataInputStream (new

		Bufferedinputstream (New FileInputStream (datafile));
		Double Price;
		int unit;
		String desc;
		Double total = 0.0;
		        try {while (true) {price = In.readdouble ();
		        Unit = In.readint ();
		        desc = In.readutf (); System.out.format ("You ordered%d" + "units Of%s at $%.2f%n ", Unit, DESC, price);
		    Total + = unit * PRICE;
		The catch (Eofexception e) {System.out.println (read the end of file); The public static void out () throws FileNotFoundException, IOException {dataoutputstream out = new DataOutputStream
		New Bufferedoutputstream (New FileOutputStream (datafile));
		    for (int i = 0; i < prices.length i + +) {out.writedouble (prices[i]);
		    Out.writeint (Units[i]);
		Out.writeutf (Descs[i]);
	} out.close (); }
Object Streams

Just as data stream supports I/O operations for basic data types, object stream is used to support I/O operations on objects, but objects that can I/O are limited, and this object must support serialization. They usually implement the serializable interface;

The class of the object stream is ObjectInputStream and ObjectOutputStream, which implements the ObjectInput and ObjectOutput interfaces (the sub-interfaces of Datainput and DataOutput). This means that all of the basic data type I/O operations are implemented in the object stream, so the object stream can contain both the base data type and the reference data type.

Import java.io.*;
Import Java.math.BigDecimal;

Import Java.util.Calendar;

    public class Objectstreams {static final String datafile = "InvoiceData"; Static final bigdecimal[] prices = {New BigDecimal ("19.99"), New BigDecimal ("9.99"), New Bigdec
    iMAL ("15.99"), New BigDecimal ("3.99"), New BigDecimal ("4.99")};
    Static final int[] units = {12, 8, 13, 29, 50}; Static final string[] Descs = {"Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Ja

    VA Pin "," Java Key Chain "};  public static void Main (string[] args) throws IOException, ClassNotFoundException {ObjectOutputStream
        out = null; try {out = new ObjectOutputStream (bufferedoutputstream) (New FileOutputStream (datafile)

            ));
            Out.writeobject (Calendar.getinstance ()); for (int i = 0; i < prices.length i + +) {Out.writeobject(Prices[i]);
                Out.writeint (Units[i]);
            Out.writeutf (Descs[i]);
        finally {out.close ();
        } objectinputstream in = null;

            try {in = new ObjectInputStream (new Bufferedinputstream (New FileInputStream (datafile)));
            Calendar date = null;
            BigDecimal Price;
            int unit;
            String desc;

            BigDecimal total = new BigDecimal (0);

            Date = (Calendar) in.readobject ();

            System.out.format ("On%ta,%<tb%<te,%<ty:%n", date);
                    try {while (true) {price = (BigDecimal) in.readobject ();
                    Unit = In.readint ();
                    desc = In.readutf ();
                    System.out.format ("You ordered%d units of%s in $%.2f%n", Unit, DESC, price); Total = Total.add (price.multiply (New BIGDECIMAl (unit)));
        The catch (Eofexception e) {} System.out.format ("For A: $%.2f%n", total);
        finally {in.close (); }
    }
}
Output and Input of Complex (complex) Objects

The methods in WriteObject and readobject all seem simple, but they contain the management logic of complex objects, which has little effect on objects that contain only basic data types, and he acts on objects that contain references to another object. In this case, writeobject iterates through the network of the entire object reference and writes all the objects in the network to the stream. Therefore, a single invocation of writeobject can cause a large number of objects to be written to the stream.

The following drawing illustrates that a object contains (b references (including D and E) and C references)


You may be puzzled when two references refer to the same object, write through the same stream, or whether they are a single object when they are read back. The answer is yes, a stream can only contain a copy of the same object, although you write two times, you actually write only two times.

But if you use two different streams, they will be a copy operation, meaning a single program that reads two streams will see two different objects.

public static void Main (string[] args) throws exception{
		
		people people = New People ("Weijinhao");
		People people2 = people;
		ObjectOutput  objectoutputstream = new ObjectOutputStream (new
				Bufferedoutputstream
						FileOutputStream ("obj"));
		Objectoutputstream.writeobject (people);
		Objectoutputstream.writeobject (people2);
		Objectoutputstream.close ();
		Do the read-
		objectinput input = new ObjectInputStream (new
				Bufferedinputstream (
						"The New FileInputStream" ("obj ")));
		People x = (people) Input.readobject (); Perform several writes, corresponding to be performed several times read
		people z = (people) Input.readobject ();
		System.out.println ("x:" + x + "Z:" + z);
		X.setage (MB);
		System.out.println ("x:" + x + "Z:" + z);
		Input.close ();
		
	}

Print as follows:

X:people [Name=weijinhao, Age=24]z:people [Name=weijinhao, age=24]
x:people [Name=weijinhao, Age=100]z:people [n Ame=weijinhao, age=100]

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.