Java I/O operations, java

Source: Internet
Author: User

Java I/O operations, java

I. Overview
Java IO supports 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
1. File class
The File class directly processes files and File systems. It does not specify how to obtain information or save the information to a File. It only describes the attributes of the File. 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 abstract path name and child path name String of parent. 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 for obtaining the standard attributes of a 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. getAbsolutePath (); // return the standard path name string System of this abstract path name. 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. stream type
In Java, different input and output sources are abstracted as "streams", 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.
For example, to read a file, 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. They increase performance by buffering input and output.
For example, enter 100 random numbers in the hello. java text and display them on the screen:

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. Overview
NIO uses the memory ing method 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: mainly contains classes related to character sets.
NIO is 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 Zone
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 that should not be read or written

  • Position: used to specify the index of the next buffer location that can be read or written
      
    There is also an optional mark that allows the program to direct position to the mark. The location is as follows:

Each time a piece of data is put, position moves one bit backward. When the Buffer loads data, call the flip method, set limit to position, and set position to 0, in this way, the read data 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 ());}}

Execution result:
  
3. Channels
The biggest difference between Channel and traditional InputStream and OutputStream is that it provides a map method through which a piece of data can be directly mapped to the memory.
Channel is an interface that provides FileChannel and other implementation classes for this interface. All channels return corresponding channels through the getChannel methods of InputStream and OutputSteam on traditional nodes.
The three most common methods in a Channel are map, read, and write. Here, map maps part or all of the data corresponding to the Channel to ByteBuffer. The read or write method has a series of overloaded forms for reading data.
Eg.copy the content of welcomeservlet.javato a.txt and print the content on the console.

Public class FileChannelTest {public static void main (String [] args) {FileChannel inChannel = null; FileChannel outChannel = null; FileChannel randomChannel = null; File f = new File ("D: // WelcomeServlet. java "); try {FileInputStream fs = new FileInputStream (f); inChannel = fs. getChannel (); MappedByteBuffer buffer = inChannel. map (FileChannel. mapMode. READ_ONLY, 0, f. length (); // map all data in inChannel to ByteBuffer Charset charset = Charset. forName ("GBK"); outChannel = new FileOutputStream ("D: // a.txt "). getChannel (); outChannel. write (buffer); buffer. clear (); CharsetDecoder decoder = charset. newDecoder (); // create the decoder object CharBuffer charBuffer = decoder. decode (buffer); // use the decoder to convert ByteBuffer to charBuffer System. out. println (charBuffer); // obtain the corresponding string} catch (FileNotFoundException e) {// catch Block e automatically generated by TODO. printStackTrace ();} catch (IOException e) {// catch Block e automatically generated by TODO. printStackTrace ();}}}

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.