Java I/O operations

Source: Internet
Author: User

Java I/O operations
I. Overview of Java IO support through java. classes and interfaces under the I/O package are completed in java. the I/O package mainly includes two types of io streams: Input and Output. Each input/output stream can be divided into two categories: byte stream and merge stream. Since JDK1.4, Java has provided a series of new APIs in the java. nio package. Through java. nio, the program can perform input and output operations more efficiently. Ii. Java I/O class and interface File class directly process files and File systems. It does not specify how to obtain or save information to files, only the attributes of the file are described. The File object is used to obtain or operate information associated with the disk File, such as the access permission, time, date, and directory path. You can also view the sub-directory hierarchy. The following constructor can be used to create a File object: constructor abstract File (File parent, String child) creates a new File instance based on the parent abstract path name and child path name String. File (String pathname) creates a new File instance by converting a given path name String to an abstract path name. File (String parent, String child) creates a new File instance based on the parent path name String and the child path name String. File (URI uri) converts a given file: URI into an abstract path to create a new File instance. The File class defines many methods to get the standard attributes of the File object. public class Demo {public static void main (String [] args) {File f = new File ("D: // hello. java "); System. out. println (f. getParent (); // returns the path string of the abstract path name parent directory. If this path name does not specify the parent directory, null System is returned. out. println (f. getName (); // return the name of the file or directory represented by the abstract path name System. out. println (f. exists (); // test whether the file or directory represented by this abstract path name has System. out. println (f. getAbsoluteFile (); // returns the absolute path name of this abstract path name in the form of System. out. println (f. getAbsolu TePath (); // return the standard path name string of this abstract path name System. out. println (f. getPath (); // converts the abstract path name to a path name string System. out. println (f. hashCode (); // calculate the hash code of this abstract path name System. out. println (f. length (); // returns the length of the file represented by the abstract path name System. out. println (f. list (); // returns an array of strings that specify the files and directories in the directory represented by the abstract path name System. out. println (f. mkdir (); // create the directory specified by this abstract path name} 2. different Input and Output sources are abstracted as "streams" in the stream-type Java, which allow? Java programs access different input and output sources in the same way. Byte stream class: provides a rich environment for processing IO targeting bytes. The top class is InputStream and OutputStream, both of which are abstract classes. Byte stream class: the byte stream class cannot process Unicode characters. The data unit of the operation is character, and the top class is Reader and Writer. The functions of the byte stream class are basically the same as those of the bytes stream class, but the data units for operations are different. InputStream and Reader both abstract the data into a pipe, and the program can read () the method extracts a "water drop" each time. You can also read multiple "water drops" using the read (char [] cbuf) method. The program uses read () the method returns-1 to determine whether the input stream ends. Eg. read the file and count the number of characters in the file: public class FileDemo {public static void main (String [] args) {int B = 0; try {FileInputStream in = null; in = new FileInputStream ("D: \ a.txt"); long num = 0; while (B = in. read ())! =-1) {System. out. print (char) B); num ++;} in. close (); System. out. println (num);} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} the FileInputStream class creates an InputStream that can be used to read files from files. Eg. copy the content of one file to another: public class FileOutStream {public static void main (String [] args) {int B = 0; try {FileInputStream in = new FileInputStream ("D: \ Eclipse \ workSpace \ day_041602 \ src \ day_041602 \ TestMain. java "); FileOutputStream out = new FileOutputStream (" D :\\ hello. java "); while (B = in. read ())! =-1) {out. write (B);} in. close (); out. close (); System. out. println ("execution completed");} catch (FileNotFoundException e) {// catch Block e automatically generated by TODO. printStackTrace ();} catch (IOException e) {// catch Block e automatically generated by TODO. printStackTrace () ;}} BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter are called buffer streams, which improve performance by buffering input and output. Eg. in hello. enter 100 random numbers in the java text, and the screen displays: public class BufferWriterDemo {public static void main (String [] args) {try {String s; bufferedWriter bw = new BufferedWriter (new FileWriter ("D: \ hello. java "); BufferedReader br = new BufferedReader (new FileReader (" D: \ hello. java "); for (int I = 0; I <100; I ++) {s = String. valueOf (Math. random (); // generates a random number bw. write (s); // write hello. bw. newLine (); // write a linefeed} bw. flush (); // Refresh the buffer while (s = br. readLine ())! = Null) // read a text line {System. out. println (s);} bw. close (); br. close ();} catch (IOException e) {// catch Block e automatically generated by TODO. printStackTrace () ;}}iii. NIO 1. summary NIO uses memory ing to process input and output, and maps a part of a file or file to the memory, so that the file can be accessed just like the memory. Related packages include: java. nio. channels package: mainly contains classes related to Channel and Selector, java. nio. charset package: It mainly contains the class NIO related to character sets based on two basic elements: Buffer and channel. The buffer zone can accommodate data and open connections to the I/O devices of the Channel team. In general, if you use the NIO system, you need to obtain the I? O a channel of the device and a buffer that holds data. Then, you can operate on the buffer and input and output data at will. In addition, NIO provides Charset classes for ing Unicode strings into byte sequences and inverse ing operations, as well as Selector classes that support non-blocking input and output. 2. buffer can be understood as a container. Its essence is an array. All objects sent to the Channel must be put in the buffer first, the data read from the channel must also be read to the buffer first. Buffer has three important parameters: capacity: indicates the maximum storage capacity of the Buffer limit: The first Buffer Location index position that should not be read or written: it is used to specify the next buffer Location index that can be read or written. In addition, there is an optional mark that allows the program to directly locate the position at the mark. The position is as follows: each time a data is put in, the position moves one bit backward. After the Buffer is loaded into the data, call the flip method and set limit to the position of the position, set position to 0 so that data read from the Buffer always starts from 0. After the Buffer output data is complete, the Buffer calls the clear method, which sets the position to 0 and the limit to capacity, so as to prepare for loading data into the Buffer again. The Buffer also provides put and get methods to put data into the Buffer and read data. It supports both single data access and batch data access. 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 ());}}

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.