The beauty of Java [from cainiao to masters] I/O in Java

Source: Internet
Author: User
Tags string splitter

In-depth analysis of Java I/O Working Mechanism

Author: Egg

Email: xtfggef@gmail.com

Weibo: http://weibo.com/xtfggef

Blog: http://blog.csdn.net/zhangerqing

Forum: http://www.qtlife.net (casually built a, convenient for everyone to communicate !)

I/O is an important part of Java and many programming languages. At the same time, many program bottlenecks and time-consuming operations are also in I/O. Therefore, solving Io problems can be of great help to improve the procedural level! In this chapter, we will systematically analyze Java Io. Through Theoretical and Practical Analysis, we hope that readers can fully understand and master it. This chapterThe beauty of Java [from cainiao to masters] SeriesJava Io. Through this chapter, readers can learn a lot about Io. Understanding, analyzing, and practicing in projects in the future can be used flexibly!

I. Introduction

Io operations are faced with many problems, such as the huge amount of information and the network environment, because Io is not only an operation on local files and directories, but sometimes a binary stream and some network resources, therefore, Io operations are time-consuming and complex for multiple reasons. Java's support for Io is a process of continuous evolution. After a lot of optimization, it became stable only after jdk1.4. In jdk1.4, NiO class was added, we have solved many performance problems. Although we have enough reason not to know about the previous situation of Java Io, we plan to study the current class well, you can thoroughly understand the IO mechanism by understanding the optimization of classes! Java Io is mainly in the Java. Io package, which is divided into nearly 80 categories:

1. byte-based I/O interfaces: inputstream and outputstream

2. character-based I/O interfaces: writer and Reader

3. disk-based I/O interfaces: File

4. Network-based I/O interface: socket (not in the Java. Io package)

I/O performance is affected by two major factors: data format and storage method. The first two types are mainly data format, and the last two are storage methods: local and network. Therefore, planning these two activities will help us to properly use Io.

Ii. byte-based I/O operations (inputstream and outputstream)

Let's take a look at the class diagram:

Figure 1

Figure 2

The two are similar. I will only detail the inputstream class, and leave outputstream for everyone to learn. The inputstream class is an abstract class. The core methods are read (), read (byte B []), read (byte B [], int off, int Len ), these three methods are the underlying methods used to read data. They can be used to read these types of data:

A. byte array

B. String object

C. File

D. pipe, entering from one end and outputting from the other end

E. Stream

F. Internet Resources

Each data source has a corresponding inputstream subclass. Because inputstream is a class at the top level, classes used to process various data sources inherit the inputstream class. Let's take a look at these classes:

Bytearrayinputstream: class used to process byte arrays. It allows the memory buffer to be used as inputstream.

Stringbufferinputstream: converts a string to an inputstream. The internal implementation uses stringbuffer.

Fileinputstream: reads data from a file.

Pipedinputstream: used to read data from a pipeline.

Sequenceinputstream: converts multiple stream objects into one inputstream.

Filterinputstream: decorator class that provides functions for other inputstream classes.

I have done on the IO operation readers know, we rarely use which class to achieve Io operations, usually is a combination of several classes to use, which actually reflects a decorative device mode (see: http://blog.csdn.net/zhangerqing) in the subsequent analysis, we will analyze in detail. As shown in figure 1, although filterinputstream is a subclass of inputstream, it is still the parent class of bufferedinputstream, datainputstream, linenumberinputstream, and pushbackinputstream, these four classes provide methods that are best suited to our programmers, such as readint (), readint (), and readint. Io operations, whether on disk or network, are performed on bytes. The programs we write at ordinary times are in the character format. Therefore, they need to be converted during transmission. In the conversion process from character to byte, we need to use a class: inputstreamreader.

3. character-based I/O operations (writer and reader)

Figure 3

Figure 4

The writer and reader operations aim to operate characters and non-bytes, and work with inputstream and outputstream to increase the IO effect. Using inputstreamreader and outputstreamreader, you can convert bytes and characters. The purpose of designing writer and reader is to internationalize and enable Io operations to support 16-bit Unicode. I will draw them separately, because if they are all painted, they will be too big to fit. If you are interested, you can import the JDK class diagram in Rational Rose to see it, which is quite enjoyable!

4. disk-based I/O operations (file)

V. Network-based I/O operations (socket)

Vi. Nio

Part 4-6 has not been completed due to the time relationship, and will be supplemented later!

VII. Classic I/O operations

1. buffer the input file.

import java.io.BufferedReader;import java.io.FileReader;public class InputStreamTest {public static String read(String filename) throws Exception {BufferedReader br = new BufferedReader(new FileReader(filename));String s;StringBuffer sb = new StringBuffer();while ((s = br.readLine()) != null) {sb.append(s + "\n");}br.close();return sb.toString();}public static void main(String[] args) throws Exception {System.out.println(read("src/InputStreamTest.java"));} }

This Code reads the inputstreamtest. Java file from the disk and converts it to a string. Output is to output the source file as is.

2. Read from memory.

import java.io.StringReader;public class MemoryInput {public static void main(String[] args) throws Exception {StringReader in = new StringReader(InputStreamTest.read("src/MemoryInput.java"));int c;while ((c = in.read()) != -1)System.out.println((char) c);}}

Read returns int type data. Therefore, char is used in the output statement to perform forced conversion. This program will output characters one by one.

3. Basic file output.

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.PrintWriter;import java.io.StringReader;public class BasicFileOutput {static String file = "basie.out";public static void main(String[] args) throws Exception {BufferedReader in = new BufferedReader(new StringReader(InputStreamTest.read("src/BasicFileOutput.java")));PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));int lineCount = 1;String s;while ((s = in.readLine()) != null) {out.println(lineCount++ + ": " + s);}out.close();System.out.println(InputStreamTest.read(file));}}

Output:

1: Import java. Io. bufferedreader;

2: Import java. Io. bufferedwriter;

3: Import java. Io. filewriter;

...

4. randomaccessfile

Randomaccessfile is called a self-independent class because it is independent of the I/O class we mentioned earlier. It has nothing to do with inputstream and outputstream, except for implementing the dataoutput and datainput interfaces. All methods are rewritten, and many of them are native methods. Let's take a look at an example to learn about this class:

5. Pipeline Flow

8. Standard I/O

These are the most primitive classes and methods we use to input or output from the console, such as system. In And system. Out.

public class StandardIO {public static void main(String[] args) throws IOException {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String s;while ((s = in.readLine()) != null && s.length() != 0)System.out.println(s);}}

System. In returns unwrapped inputstream objects, so decoration is required. The inputstreamreader is converted to a reader object and placed in the bufferedreader constructor. In addition, system. Out and system. Err are both direct priintstream objects and can be directly used. We can also use the handler class under the java. util package to replace the above program:

public class StandardIO {public static void main(String[] args) throws IOException {Scanner in = new Scanner(System.in);String s;while((s = in.next()) != null && s.length() != 0){System.out.println(s);}}}

IX. Performance analysis and summary

1. A file read/write tool class.

Import Java. io. bufferedreader; import Java. io. file; import Java. io. filereader; import Java. io. ioexception; import Java. io. printwriter; import Java. util. arraylist; import Java. util. arrays;/*** a very practical file operation class. 2012-12-19 ** @ author Bruce Eckel, edited by erqing **/public class textfile extends arraylist <string> {Private Static final long serialversionuid =-1942855619975442612l; // read a file as a strin Gpublic static string read (string filename) {stringbuilder sb = new stringbuilder (); try {bufferedreader in = new bufferedreader (New filereader (new file (filename ). getabsolutefile (); string s; try {While (S = in. readline ())! = NULL) {sb. append (s); sb. append ("\ n") ;}} finally {In. close () ;}} catch (ioexception e) {Throw new runtimeexception (E);} return sb. tostring ();} // write a single file in one method callpublic static void write (string filename, string text) {try {printwriter out = new printwriter (new file (filename ). getabsolutefile (); try {out. print (text);} finally {out. close () ;}} catch (ioexception e) {Throw new Runtime Exception (e) ;}// read a file, spilt by any regular expressionpublic textfile (string filename, string splitter) {super (arrays. aslist (read (filename ). split (splitter); If (get (0 ). equals ("") Remove (0);} // normally read by linespublic textfile (string filename) {This (filename, "\ n ");} public void write (string filename) {try {printwriter out = new printwriter (new file (filename ). getabsolutefile (); try {(String item: This) out. println (item);} finally {out. close () ;}} catch (ioexception e) {Throw new runtimeexception (e) ;}// test, I have generated a file named data. d At the rootpublic static void main (string [] ARGs) {/* read () test */system. out. println (read ("data. d "); // testing is OK! /* Write () test */write ("Out. d", "helloworld \ negg"); // testing is OK! /* Constractor test */textfile TF = new textfile ("data. d"); // testing is OK !}}

2. Read Binary files.

import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;/** * to read the binary file *  * @author erqing *  */public class BinaryFile {/* the parametre is a file */public static byte[] read(File file) throws IOException {BufferedInputStream bf = new BufferedInputStream(new FileInputStream(file));try {byte[] data = new byte[bf.available()];bf.read(data);return data;} finally {bf.close();}}/* the param is the path of a file */public static byte[] read(String file) throws IOException {return read(new File(file).getAbsoluteFile());}}

This chapter is not complete. Due to the recent busy schedule, you should first issue a part and complete the missing parts in the future!

 

 

Related Article

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.