I. Overview
Java IO support through the java.io package under the class and interface to complete, under the Java.io package mainly includes input, output two IO streams, each input and output stream can be divided into two categories of byte stream and character stream. From JDK1.4 onwards, Java provides a new series of APIs under the Java.nio package, and through Java.nio, the program can perform input and output operations more efficiently.
Ii. Java I/O classes and Interfaces
1. File class
The file class directly handles files and file systems, and it does not specify how to obtain information or save information to a file, describing only the properties of the file itself. The file object is used to obtain or manipulate information associated with a disk file, such as access permissions, time, date, and directory paths, and also to browse the hierarchy of subdirectories.
The following constructor can be used to create a file object:
构造方法摘要File(FileString child) File 实例。File(String pathname) File 实例。File(StringString child) File 实例。File(URI uri) fileFile 实例。
The file class defines a number of methods that can get the standard properties of a file object
Public classdemo{ Public Static void Main(string[] args) {File f=NewFile ("D://hello.java"); System. out. println (F.getparent ());//Returns the pathname string of the parent directory for this abstract pathname, or null if the pathname does not specify a parent directorySystem. out. println (F.getname ());//Returns the name of the file or directory represented by this abstract path nameSystem. out. println (F.exists ());//test whether the file or directory represented by this abstract pathname existsSystem. out. println (F.getabsolutefile ());//Returns the absolute pathname form of this abstract path nameSystem. out. println (F.getabsolutepath ());//Returns the canonical pathname string for this abstract path nameSystem. out. println (F.getpath ());//Convert this abstract pathname to a path name stringSystem. out. println (F.hashcode ());//Computes the hash code for this abstract path nameSystem. out. println (F.length ());//Returns the length of the file represented by this abstract path nameSystem. out. println (F.list ());//Returns a string array that specifies the files and directories in the directory represented by this abstract path nameSystem. out. println (F.mkdir ());//Create the directory specified by this abstract path name}}
2. Stream class
In Java, the different input and output sources are abstracted as "streams", allowing them to flow in the same way. Java programs use the same way to access different input and output sources.
BYTE Stream class: Provides a rich environment for processing bytes of Io, the top class is InputStream and OutputStream, both of which are abstract classes.
Character Stream class: The byte stream class cannot handle Unicode characters, the data unit of the character Stream class operation is a character, and the top category is reader and writer.
The function of the byte stream class and the character stream class is basically the same, except that the data unit of the operation is different, in which both InputStream and reader are abstracted data into a water pipe, the program can extract a "droplet" each time through the read () method, or it can be read (CHAR[]CBUF) method to read multiple "Drops", the program returns through the Read () method-one to determine whether the end point of the input stream is reached.
eg. read files, statistics file characters:
Public classfiledemo{ Public Static void Main(string[] args) {intb=0;Try{FileInputStreaminch=NULL;inch=NewFileInputStream ("D:\\a.txt");Longnum=0; while((b=inch. Read ())!=-1) {System. out. Print (Char) b); num++; }inch. Close (); System. out. println (num); }Catch(FileNotFoundException e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); } }}
The FileInputStream class creates a inputstream that can be used to read files from a file.
eg. copy the contents of one file to another file:
Public classfileoutstream{ Public Static void Main(string[] args) {intb=0;Try{FileInputStreaminch=NewFileInputStream ("D:\\eclipse\\workspace\\day_041602\\src\\day_041602\\testmain.java"); FileOutputStream out=NewFileOutputStream ("D:\\hello.java"); while((b=inch. Read ())!=-1) { out. write (b); }inch. Close (); out. Close (); System. out. println ("Execution Complete"); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
Bufferedinputstream, Bufferedoutputstream, BufferedReader, and bufferedwriter are called buffered streams, which improve performance by buffering input and output.
eg. enter 100 random numbers in the Hello.java text and display them on the screen:
Public classbufferwriterdemo{ Public Static void Main(string[] args) {Try{String s; BufferedWriter bw=NewBufferedWriter (NewFileWriter ("D:\\hello.java")); BufferedReader br=NewBufferedReader (NewFileReader ("D:\\hello.java")); for(intI=0;i< -; i++) {s=string.valueof (Math.random ());//Generate random numbersBw.write (s);//write to the Hello.java fileBw.newline ();//write a line break} bw.flush ();//Refresh buffer while((S=br.readline ())! =NULL)//Read a line of text{System. out. println (s); } bw.close (); Br.close (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
Iii. NIO
1. Overview
NIO uses memory-mapped methods to process input and output, mapping a section of a file or file into memory so that it can be accessed like memory.
The related packages are: Java.nio.channels package: mainly includes channel and selector related classes, Java.nio.charset package: main contains and character set related classes
The NIO system is based on two basic elements: buffers and channels. The buffer holds data, and the channel team is an open connection to the I/O device. In general, the NIO system is used to obtain the I? o A channel of the device and a buffer that holds the data, which can then operate on the buffer, optionally entering and outputting data. In addition to this, NIO also provides charset classes for mapping Unicode strings into byte sequences and inverse mapping operations, as well as selector classes that support non-blocking input and output.
2. Buffers
Buffering (buffer) can be understood as a container, which is essentially an array, and all objects sent to the channel must first be placed in buffer, and the data read from the channel must first be read into buffer.
There are three important parameters in buffer
-
Capacity: Indicates the maximum storage capacity for this buffer
-
Limit: The first buffer position index that should not be read out or written
-
Position: Used to indicate the next buffer position index that can be read out or written to
In addition to an optional mark Mark, the Mark allows the program to direct the position to mark. The location is as follows:
Each time a data is placed, the position moves backwards, and when buffer loads the data, the flip method is called, the limit is set to the location of position, and the position is set to 0 so that the read data from buffer always starts at 0. When the buffer output data is finished, buffer calls the clear method, which resets the position to 0 and the limit to capacity, which prepares the data to be loaded again into buffer. Buffer also provides a put and get method for putting data into buffer and reading data, supporting access to both individual data and bulk data.
eg.
public class test{public static void Main (string[] args) {Charbuffer M=charbuffer. Allocate(8);M. Put(' A ');M. Put(' B ');M. Put(' C ');System. out. println("Position:"+m. Position());System. out. println("Limit:"+m. Limit());M. Flip();System. out. println("first element"+m. Get());System. out. println("second element"+m. Get());System. out. println("Position:"+m. Position());}}
Execution Result:
3. Channel
The biggest difference between channel and traditional InputStream and OutputStream is that it provides a map method that maps a piece of data directly into memory.
Channel is an interface, the system provides the interface FileChannel and other implementation classes, all the channel is the traditional node InputStream, Outputsteam Getchannel method to return the corresponding channel.
The three most common methods of channel are: map, read, and write. where map Bytebuffer,read or write methods for some or all of the data mappings corresponding to the channel have a series of overloaded forms for reading data.
eg. copy the contents of the Welcomeservlet.java to the A.txt and print the contents at the console.
Public classfilechanneltest{ Public Static void Main(string[] args) {FileChannel inchannel=NULL; FileChannel outchannel=NULL; FileChannel randomchannel=NULL; File f=NewFile ("D://welcomeservlet.java");Try{FileInputStream fs=NewFileInputStream (f); Inchannel=fs.getchannel (); Mappedbytebuffer Buffer=inchannel.map (FileChannel.MapMode.READ_ONLY,0, F.length ());//Map all the data in Inchannel into BytebufferCharset Charset=charset.forname ("GBK"); Outchannel=NewFileOutputStream ("D://a.txt"). Getchannel (); Outchannel.write (buffer); Buffer.clear (); Charsetdecoder Decoder=charset.newdecoder ();//Create decoder objectCharbuffer charbuffer=decoder.decode (buffer);//Use decoder to convert Bytebuffer to CharbufferSystem. out. println (Charbuffer);//Get the corresponding string}Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
I/O operations for Java