The various streams of IO have been described earlier, and we know that I/O streams can be combined in different ways. Introduces several typical I/O usage methods;
1. Buffered file reads
Open a file and read the characters in it, you can use a string or a file object as the Fileinputreader of the file name.
As follows:
Packageiostreamtest;ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException; Public classBufferdinputfile { Public StaticString read (string filepath)throwsioexception{FileReader Filere=NewFileReader (NewFile (filepath)); intch; StringBuilder SB=NewStringBuilder (); while((Ch=filere.read ())!=-1) {sb.append (CH); SYSTEM.OUT.PRINTLN (CH); } filere.close (); returnsb.tostring (); } Public Static voidMain (String args[])throwsioexception{System.out.println (Read ("Fortest")); }}
Input file: fortest
Only one character of one character reads the result as follows, output:
To increase the speed, you can use BufferedReader to read as follows:
Packageiostreamtest;ImportJava.io.BufferedReader;ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException; Public classBufferdinputfile { Public StaticString read (string filepath)throwsioexception{BufferedReader Bufre=NewBufferedReader (NewFileReader (NewFile (filepath)); StringBuilder SB=NewStringBuilder (); String s; intCh=0; while((Ch=bufre.read ())!=-1) {sb.append (CH); } /*while ((S=bufre.readline ())!=null) sb.append (s+ "\ n");*/Bufre.close (); returnsb.tostring (); } Public Static voidMain (String args[])throwsioexception{System.out.println (Read ("Fortest")); }}
The result is the same.
Bufferreader provides ReadLine methods, and FileReader only provides
A, int read (); Reads a single character. Returns the character read as an integer, or 1 if the end of the stream has been reached.
B. int read (char []cbuf);//Read the characters into the array. Returns the number of characters read. Returns 1 if the trailer has reached the end
2 Input from memory
The string read from Bufferedinputfile.read is used to create a stringreader and then call read one character at a time and send it to the console.
public static void Main (String args[]) throws ioexception{stringreader sr = new StringReader (Buffer Dinputfile.read ("Fortest" int ch=0; while ((Ch=sr.read ())!=-1 char ) ch); // Note that read returns the next byte as an int, so it is converted to char to print correctly. } // system.out.println (Read (" Fortest ")); }
3. Formatted memory input
To read formatted data, you can use DataInputStream, which is byte-oriented IO. So use InputStream instead of reader.
Public Static void throws ioexception{ new datainputstream (new Bytearrayinputstream ( Bufferdinputfile.read ("Fortest"). GetBytes ())); while (Datain.available ()!=0) { //because ReadByte reads one character at a time, the value of any byte is a legitimate result, so the return value cannot be used to verify the end of the input. Instead, we can use available ()
How many more access characters are checked System.out.println ((char) datain.readbyte ());} }
4. Basic file output
FileWriter writes data to a file. Typically, creating a filewriter that is linked to a specified file is actually wrapped in bufferedwriter to cache the output. It can be packaged as an arbitrary output stream as needed. In this packaging city PrintWriter
In Javase5, the decoration work can be omitted. Added Auxiliary constructor (PrintWriter pw = new Printwirter (file)). PrintWriter can format the data for easy reading.
ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileWriter;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.io.StringReader; Public classBufferedoutputtest { Public Static voidMain (String args[])throwsioexception{BufferedReader bufr=NewBufferedReader (NewStringReader (Bufferdinputfile.read ("read"))); PrintWriter PW=NewPrintWriter//(New File ("Fortest"));(NewBufferedWriter (NewFileWriter ("Fortest"))); intLineCount =1; String s; while((S=bufr.readline ())! =NULL) pw.println (LineCount++ +":"+s); Pw.close (); //System.out.println (Bufferdinputfile.read ("fortest")); }}
5. Storing and recovering data
You can write data from DataOutputStream and use DataStream to recover data.
Java guarantees that we can use DataInputStream to read data accurately, regardless of how different the read-write platform is.
Packageiostreamtest;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.DataInputStream;ImportJava.io.DataOutputStream;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException; Public classDataout_inputstream { Public Static voidMain (String args[])throwsioexception{DataOutputStream Datao=NewDataOutputStream (NewBufferedoutputstream (NewFileOutputStream ("Fortest"))); Datao.writeint (9); Datao.writeutf ("Mark"); Datao.writebyte (9); Datao.close (); DataInputStream DataIn=NewDataInputStream (NewBufferedinputstream (NewFileInputStream ("Fortest"))); System.out.println (Datain.readint ()); System.out.println (Datain.readutf ()); }}
6. Read and write random access files. Randomaccessfile
Similar to the combined use of dataoutput and DataInputStream.
Random is suitable for files made up of records of known size. You can use seek to transfer records from one place to another. The Datainput and DataOutput interfaces are implemented, not inherited from OutputStream or InputStream. Support the search method, you can query the location of the file where the point (Getfilepointer ());
7. Pipe flow. used for communication between multiple tasks, that is, for concurrency. Pipeinputstream Pipeoutputstream,pipereader Piperwriter and so on.
How Java I/O is typically used