Simple input and output of Java IO

Source: Internet
Author: User

Io in Java is divided into two parts, with InputStream and reader as the base class input classes, and OutputStream and writer as the base class output classes. where InputStream and OutputStream io in bytes, while reader and writer are in characters.

In addition to input and output, there are a number of class libraries called filter, or adorners. For derived classes that enter available FilterInputStream and FilterReader, output derived classes that are available Filteroutputstream and Filterwriter, Where FilterInputStream and Filteroutputstream are in bytes, FilterReader and Filterwriter are in character units.

There is also a separate-randomaccessfile with InputStream and outputstream, used to read and write to the file, somewhat similar to the C language of fopen ()

So it can be concluded that all streams ending with a stream are in bytes, as well as flows; the end of reader or writer is in characters. Reader and writer appear in java1.1, and if you need to convert, you can use InputStreamReader and OutputStreamWriter.

Filters (Filter)

Filter is some control over input or output, such as caching, reading, or writing basic data types, to change some of the behavior of the stream.

Derived classes for FilterInputStream:

Derived classes for Filteroutputstream:

The filter used in reader and writer contrasts with the filter in InputStream and OutputStream:

The specific use of filter will be described in a concrete comprehensive example.

Input

Input is divided into input bytes and input characters, respectively, using the base class is InputStream and reader, if you need to convert Inputstrema to reader, you can use InputStreamReader. The following are some of the derived classes that are commonly used by InputStream and which writer corresponds to.

InputStream Derived classes:

The derived class to which reader corresponds:

To turn InputStream into a reader example:

// 创建一个InputStream类型的对象innew FileInputStream("data.txt");// InputStreamReader继承自Reader,其构造方法接受一个InputStream对象new InputStreamReader(in);
Output

Output is divided into output bytes and output characters, respectively using the base class is OutputStream and writer, if you need to convert Outputstrema to writer, you can use OutputStreamWriter. The following are some of the derived classes that are commonly used by OutputStream and which writer corresponds to.

OutputStream Derived classes:

The derived class to which writer corresponds:

To turn OutputStream into a writer example:

// 创建一个OutputStream类型的对象out=new FileOutputStream("data.txt");// OutputStreamWriter继承自Writer,其构造方法接受一个OutputStream对象Writer writer=new OutputStreamWriter(out);
Comprehensive example

1. Open a file and put the contents of it on line output screen. To improve efficiency, the first filter BufferedReader is used to buffer the input.

 Public classRead { Public Static void Main(String[]args) throws exception{String file="Data.txt";    Read (file); } Public Static void Read(String file) throws exception{BufferedReaderinch=NewBufferedReader (NewFileReader (file)); String s; while((s=inch. ReadLine ())! =NULL) System. out. println (s);inch. Close (); }}

2, from the file in bytes read content, need to use the DataInputStream filter, because here to operate on the byte, so use InputStream instead of reader. Which is the efficiency comparison with BufferedStream.

Import java.io.*; Public classReadByte { Public Static void Main(string[] args) throws Exception {String file ="Data.txt";LongStart Start = System.currenttimemillis ();//Record run start timeReadwithbufferedinputstream (file); System. out. println ("Readwithbufferedinputstream Use time:"+ (System.currenttimemillis ()-start));//Run end time-start time is run timeStart = System.currenttimemillis ();        Readwithoutbufferedinputstream (file); System. out. println ("Readwithoutbufferedinputstream Use time:"+ (System.currenttimemillis ()-start)); } Public Static void Readwithbufferedinputstream(String file) throws Exception {//Use Bufferedinputstream to read filesDataInputStreaminch=NewDataInputStream (NewBufferedinputstream (NewFileInputStream (file)); while(inch. available ()! =0)///DataInputStream The remaining number of characters is nonzero indicates that no output has ended            inch. ReadByte ();inch. Close (); } Public Static void Readwithoutbufferedinputstream(String file) throws Exception {//Do not bufferedinputstream read filesDataInputStreaminch=NewDataInputStream (NewFileInputStream (file)); while(inch. available ()! =0)inch. ReadByte ();inch. Close (); }}

Run the program, where the Data.txt file size is 5.4M, and the output on my computer is:

usetime:8775usetime:18487

Obviously the use of bufferedinputstream is much more efficient.

3, java1.5 later in order to facilitate the input of the file, added a printwrite filter, which encapsulates the bufferedwriter, and can accept the string type file name, so you can streamline the code.

Import java.io.*; Public classFileOutPut { Public Static void Main(String[]args) throws exception{BufferedReaderinch=NewBufferedReader (NewFileReader ("Data.txt")); PrintWriter out=NewPrintWriter ("Data1.txt"); String s;LongStart=system.currenttimemillis (); while((s=inch. ReadLine ())! =NULL){ out. println (s);//When reading a file with ReadLine, the carriage return of each line is removed, so write the carriage return when writing to the file} System. out. println ("Use time:"+ (System.currenttimemillis ()-start));inch. Close (); out. Close (); }}

Running the file can also be found, the same size as the Data.txt file, read out and write very fast, this benefit from the cache.

4, because the previous method to write to the file is a byte or character, there is no way to store some basic types, so use Dataoutputstream/datainputstream.

Import java.io.*; Public classReadandwritebasetype { Public Static void Main(string[] args) throws Exception {DataOutputStream out=NewDataOutputStream (NewFileOutputStream ("Data1.txt")); out. writeUTF ("This a String");//write String to use writeUTF ();         out. Writeint (5); out. Writefloat (5.4f); out. Close (); DataInputStreaminch=NewDataInputStream (NewFileInputStream ("Data1.txt")); System. out. println (inch. Readfloat ()); System. out. println (inch. ReadInt ()); System. out. println (inch. readUTF ());//read out the string to use readUTF ();        inch. Close (); }}

5, using Randomaccessfile to read and write files a bit similar to dataoutputstream/datainputstream, you need to specify the data type. However, Randomaccessfile needs to determine the type of operation for the file when creating the object, R/W/RW is read-only, write-only, read and write, respectively. The Seek () method can be moved around to modify the content anywhere in the file

Import Java. IO.*;public class Usingrandomaccessfile {public static void main (string[] args) throws Exception {Randomaccessfile RF = new Randomaccessfile ("Data1.txt","RW");Rf. Writeint(5);Rf. Writeint(Ten);Rf. Writeint( the);Rf. Writeint( -);Rf. Close();RF = new Randomaccessfile ("Data1.txt","R");System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());Rf. Close();RF = new Randomaccessfile ("Data1.txt","RW");Rf. Seek(0);//Pointing the pointer at the beginning of the fileRf. Writeint(-1);//Change the first two bytes to 1Rf. Seek(0);System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());System. out. println(RF. ReadInt());Rf. Close();}}

6, the standard input with BufferedReader packaging and get keyboard input

publicclass Systemin {    publicstaticvoidmain(String[] args) throws Exception {        // System.in为InputStream类型,要通过InputStreamReader将其转换成Reader        innew BufferedReader(new InputStreamReader(System.in));        String s;        whileinnull) {            System.out.println(s);        }    }}

6, redirect, the console output, error output directed to a file, can be used to write log files

Import java.io.*; Public classRedirect { Public Static void Main(string[] args) throws Exception {OutputStream console = System. out; PrintStream out=NewPrintStream (NewBufferedoutputstream (NewFileOutputStream ("Data1.txt"))); BufferedReaderinch=NewBufferedReader (NewInputStreamReader (NewFileInputStream ("Data.txt"))); System.setout ( out);//redirect output to outSystem.seterr ( out);//redirect error messages to outString s; while(s =inch. ReadLine ())! =NULL) System. out. println (s);//output is directed to out, so the console output is not         out. Close ();inch. Close (); }}

Simple input and output of Java IO

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.