Java Io--bio (i)

Source: Internet
Author: User
Tags new set

I. Java IO Overview 1.1 related concepts Java IO

Java IO is the Java input and output system. No matter what kind of application we write, it is unavoidable to deal with various kinds of input and output related media, in fact, the process of IO with the media is very complex, this has to consider a lot of factors, such as what we want to consider and which medium for IO (file, console, network), we also have to consider the specific and their means of communication , binary, by character, by word, by line, and so on). The Java Class Library designer overcomes these challenges by designing a number of classes, which are located in the java.io package.

After JDK1.4, in order to improve the efficiency of Java IO, Java also provided a new set of Io,java new IO abbreviation java NIO. It provides high-speed block-oriented IO operations in standard Java code. This article focuses on the BIO of Java IO

Flow

In Java io, a stream is a core concept. A stream is conceptually a continuous stream of data. You can either read the data from the stream or write data to the stream. The stream is associated with the data source or the medium in which the data flows. In Java IO, it can be either a stream of bytes (read and write in bytes) or a character stream (read and write in characters).

IO-related media

Java's IO package focuses on reading from the original data source and outputting the raw data to the target medium. The following are the most typical data sources and target vectors:

    • File
    • Pipeline
    • Network connection
    • Memory Cache
    • System.in, System.out, System.error (Note: Java standard input, output, error output)
Ii. framework of the Java IO Class Library 2.1 Types of Java IO

Although the Java IO Class library is large, its framework is clear in general. From the perspective of reading media or writing medium, Java IO can be divided into:

    1. Input stream: InputStream and Reader
    2. Output stream: OutputStream and writer

And from the dimension of the type of its processing stream, Java IO can be divided into:

    1. BYTE stream: InputStream and OutputStream
    2. Character streams: Reader and writer

The following picture clearly describes the classification of the Javaio:

- Byte stream character Stream
Input stream InputStream Reader
Output stream OutputStream Writer

Our program needs to read data from the data source via InputStream or reader, and then write the data to the target medium using OutputStream or writer. Where InputStream and reader are associated with the data source, OutputStream and writer are associated with the target medium. The following figure illustrates this:

2.2 IO Class Library

Above we introduce four kinds of Java IO:inputstream, OutputStream, Reader, Writer, in fact, in our actual application, we use the general is their subclasses, the reason why so many sub-categories, The goal is for each class to be responsible for different functions so that we can develop a variety of applications. Summary of various uses are as follows:

    • File access
    • Network access
    • Memory Cache Access
    • Thread internal communication (pipeline)
    • Buffer
    • Filter
    • Analytical
    • Read-write text (readers/writers)
    • Read and write basic type data (long, int etc.)
    • Read and Write objects

Let's take a look at the two graphs to get a general picture of the inheritance of these classes and their effects.

Figure 1:java Integration Relationship of IO class

Figure 2:java The media responsible for each class in IO

Iii. basic usage of Java IO 3.1 java IO: byte stream

We already know from the above that the classes corresponding to the byte stream should be inputstream and OutputStream, and in our actual development we should choose the corresponding subclass according to the different media types. Below we will use the byte stream to manipulate the file medium:

Example 1, writing a file with a byte stream

  public static void writeByteToFile() throws IOException{        String hello= new String( "hello word!");         byte[] byteArray= hello.getBytes();        File file= new File( "d:/test.txt");         //因为是用字节流来写媒介,所以对应的是OutputStream          //又因为媒介对象是文件,所以用到子类是FileOutputStream        OutputStream os= new FileOutputStream( file);         os.write( byteArray);         os.close();  }

Example 2, reading a file with a byte stream

public static void readByteFromFile() throws IOException{        File file= new File( "d:/test.txt");         byte[] byteArray= new byte[( int) file.length()];         //因为是用字节流来读媒介,所以对应的是InputStream         //又因为媒介对象是文件,所以用到子类是FileInputStream        InputStream is= new FileInputStream( file);         int size= is.read( byteArray);        System. out.println( "大小:"+size +";内容:" +new String(byteArray));         is.close();  }
3.2 Java IO: Character stream

Similarly, the classes corresponding to the character stream should be Reader and Writer. Here we will use a character stream to manipulate the file media:

Example 3, writing a file with a character stream

public static void writeCharToFile() throws IOException{        String hello= new String( "hello word!");        File file= new File( "d:/test.txt");         //因为是用字符流来读媒介,所以对应的是Writer,又因为媒介对象是文件,所以用到子类是FileWriter        Writer os= new FileWriter( file);         os.write( hello);         os.close();  }

Example 4, reading a file with a stream of characters

  public static void readCharFromFile() throws IOException{        File file= new File( "d:/test.txt");         //因为是用字符流来读媒介,所以对应的是Reader         //又因为媒介对象是文件,所以用到子类是FileReader        Reader reader= new FileReader( file);         char [] byteArray= new char[( int) file.length()];         int size= reader.read( byteArray);        System. out.println( "大小:"+size +";内容:" +new String(byteArray));         reader.close();  }
3.3 Java IO: Byte stream converted to character stream

The byte stream can be converted into a character stream, the InputStreamReader class provided in the Java.io package can be implemented, of course, it can be seen from the name of its role. In fact this involves another concept, the combination of IO streams, which we describe in detail later. Let's look at a simple example:

Example 5, byte stream converted to character stream

public static void convertByteToChar() throws IOException{        File file= new File( "d:/test.txt");         //获得一个字节流        InputStream is= new FileInputStream( file);         //把字节流转换为字符流,其实就是把字符流和字节流组合的结果。        Reader reader= new InputStreamReader( is);         char [] byteArray= new char[( int) file.length()];         int size= reader.read( byteArray);        System. out.println( "大小:"+size +";内容:" +new String(byteArray));         is.close();         reader.close();  }
3.4 Combination of Java Io:io classes

We know from the example of the above byte stream into a character stream that the IO flow can be combined (or nested), but the purpose of the combination is simple, which is to combine the characteristics of multiple classes to achieve more functionality. The combination is simple, and can be achieved by placing one stream in the constructor of another stream, with two streams being combined, and three or more streams grouped together. Of course, not all flows can be combined. About the combination is not too much introduction, the following examples are many used in the combination, we have a good experience can be.

3.5 Java IO: File Media operations

File is the most commonly used read-write medium in Java io, so we'll do a little more about it here.

3.5.1 File Media

Example 6, file operation

public class Filedemo {public static void main (string[] args) {//Check the file for the existence of the files = new file ("D:/test         . txt ");        Boolean fileexists = File.exists (); System.         Out.println (fileexists);         Creates a file directory that returns false if the parent directory does not exist file File2 = new file ("D:/fatherdir/subdir");        Boolean dircreated = File2.mkdir (); System.         Out.println (dircreated);         Create a file directory, and if the parent directory does not exist, create file File3 = new file ("D:/fatherdir/subdir2") together with the parent directory;        Boolean dirCreated2 = File3.mkdirs (); System.        Out.println (DIRCREATED2);         File file4= New file ("D:/test.txt");         Judgment length Long length = File4.length ();         Rename file Boolean isrenamed = File4.renameto (new file ("D:/test2.txt"));        Delete file Boolean isDeleted = File4.delete ();         File file5= New file ("D:/fatherdir/subdir");         is the directory Boolean isdirectory = File5.isdirectory ();         List file name string[] FileNames = File5.list (); List Directory        file[] files = file4.listfiles (); }

}

3.5.3 Random Read of file files

From the above example we already know that we can use FileInputStream (file character stream) or filereader (file byte stream) to read the file, these two classes allow us to read the file contents in characters and bytes respectively, but they all have a disadvantage, Just start reading from the file header and read the end of the file.

But sometimes we just want to read part of the file, or random read the file, then we can use randomaccessfile. Randomaccessfile provides a seek() method for locating the pointer to the file to be read and written, and we can also call the getFilePointer() method to get the position of the current pointer, as shown in the following example:

Example 7, Random Read file

  public static void randomAccessFileRead() throws IOException {         // 创建一个RandomAccessFile对象        RandomAccessFile file = new RandomAccessFile( "d:/test.txt", "rw");         // 通过seek方法来移动读写位置的指针         file.seek(10);         // 获取当前指针         long pointerBegin = file.getFilePointer();         // 从当前指针开始读         byte[] contents = new byte[1024];         file.read( contents);         long pointerEnd = file.getFilePointer();        System. out.println( "pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n" + new String(contents));         file.close();  }

Example 8, random write file

  public static void randomAccessFileWrite() throws IOException {         // 创建一个RandomAccessFile对象        RandomAccessFile file = new RandomAccessFile( "d:/test.txt", "rw");         // 通过seek方法来移动读写位置的指针         file.seek(10);         // 获取当前指针         long pointerBegin = file.getFilePointer();         // 从当前指针位置开始写         file.write( "HELLO WORD".getBytes());         long pointerEnd = file.getFilePointer();        System. out.println( "pointerBegin:" + pointerBegin + "\n" + "pointerEnd:" + pointerEnd + "\n" );         file.close();  }
3.6 Java IO: Pipeline Media

Pipelines are primarily used to communicate with two threads in the same virtual machine. As a result, a pipeline can be both a data source medium and a target medium.

It is important to note that pipelines in Java do not have the same meaning as pipelines in unix/linux, where pipelines can be used as two medium for communication in different spatial processes, whereas in Java, pipelines can only communicate with different threads in the same JVM process. The IO classes associated with pipelines are:pipedinputstream and PipedOutputStream, let's look at an example:

Example 9, read and write pipeline

public class Pipeexample {public static void main (string[] args) throws IOException {final PipedOutputStream          Output = new PipedOutputStream ();          Final PipedInputStream input = new PipedInputStream (output);  Thread thread1 = new Thread (new Runnable () {@Override public void run () {try {Output.write ("Hello World, pipe!").                  GetBytes ());          } catch (IOException e) {}}});  Thread thread2 = new Thread (new Runnable () {@Override public void run () {try                      {int data = Input.read ();                          while (Data! =-1) {System. Out.print (char) data);                      data = Input.read ();                                   }} catch (IOException e) {} finally{try {    Input.close ();                                } catch (IOException e) {e.printstacktrace ();          }                  }              }          });          Thread1.start ();      Thread2.start (); }

}

3.7 Java IO: Network media

About Java IO for network media operations, Java Network Programming , the core is the socket, as with disk operations, Java Network programming corresponds to two sets of APIs, namely Java IO and Java NIO, about which I will prepare a special article to introduce.

3.8 Java Io:bufferedinputstream and Bufferedoutputstream

Bufferedinputstream , as the name implies, provides a buffer to improve IO efficiency when writing to a stream. In the case of disk or network IO, the original inputstream to the data read process is a byte-by-byte operation, and Bufferedinputstream provides a buffer inside, when reading the data, will read a large chunk of data into the buffer, This is much more efficient than single-byte operations, especially when the process disk IO and the large amount of data read and write.

Using Bufferedinputstream is simple, just combine the normal input stream and the Bufferedinputstream. We have converted the above example 2 to read the file with Bufferedinputstream, see the following example:

Example 10, reading a file with a buffered stream

  public static void readByBufferedInputStream() throws IOException {        File file = new File( "d:/test.txt");         byte[] byteArray = new byte[( int) file.length()];         //可以在构造参数中传入buffer大小        InputStream is = new BufferedInputStream( new FileInputStream(file),2*1024);         int size = is.read( byteArray);        System. out.println( "大小:" + size + ";内容:" + new String(byteArray));         is.close();  }

about how to set the buffer size, we should determine according to our hardware condition. For disk IO, if the hard disk reads a 4KB size file block each time, then we'd better set it to an integer multiple of this size. Because disk is particularly efficient for sequential reads, it can be more efficient to set the capitalization in buffer, such as 4*4KB or 8*4KB.

It is also important to note that the disk itself will have a cache, in which case, the Bufferedinputstream will read the size of the disk cache data at a time, rather than a number of times to read. So to get an optimal buffer value, we have to know the block size and its cache size for each disk read, and then the best buffer size based on the results of multiple experiments.

Bufferedoutputstream The situation and bufferedinputstream consistent, here is not much to do the description.

3.9 Java Io:bufferedreader and BufferedWriter

BufferedReader, BufferedWriter the role of basic and Bufferedinputstream, bufferedoutputstream consistent, concrete usage and principle are similar, Just one is a character stream oriented one is a byte stream oriented. Again, we will transform example 4 in the character stream, and give it the buffer function, see example:

 public static void readByBufferedReader() throws IOException {        File file = new File( "d:/test.txt");         // 在字符流基础上用buffer流包装,也可以指定buffer的大小        Reader reader = new BufferedReader( new FileReader(file),2*1024);         char[] byteArray = new char[( int) file.length()];         int size = reader.read( byteArray);        System. out.println( "大小:" + size + ";内容:" + new String(byteArray));         reader.close();  }

Reprint please indicate source, original link: http://blog.csdn.net/suifeng3051/article/details/48344587

Java Io--bio (i)

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.