Java-based file IO

Source: Internet
Author: User

Overview

Java I/O operations classes in the package java.io, about nearly 80 classes, but these classes can be divided into four groups, respectively:

Divide by processing data type: byte stream and character stream :

    • Byte-based operation of I/O interfaces: InputStream and OutputStream
    • I/O interfaces based on character manipulation: Writer and Reader

By how data is transferred: disk operations and network operations

    • Disk operation-based I/O interface: File
    • Network operation-based I/O interface: Socket

Divide by flow direction: input stream and input stream

    • To read, use the input stream, and if you want to write it, use the output stream

The first two groups are mainly based on the data transmission data format, the latter two groups are mainly based on the way of transmitting data, although the Socket class is not under the java.io package, but I still divide them together, because I personally think that the core issue of I/O is either the data format affects I/O operations, or the transmission mode impact I The/O operation, the problem of what kind of data is written, I/Os is just a means of interacting with machines or machines and machines, and in addition to being able to do this interactive function, we focus on how to improve its efficiency, and the data format and transmission mode are the most important factors that affect efficiency.

3. When do I use a byte stream? When do I use a character stream?

The first thing to know is that any data that exists on the hard disk is stored in binary form. By using a byte stream, you can read any file. The stream reads one byte at a time, and the character flow uses the byte throttle to read one or more bytes, to find the specified encoding table and return the corresponding encoding. So a character stream can only handle plain text character data, while a byte stream could handle more types of data than slices, videos, audio files, etc. Therefore, the use of character streams is preferred as long as the text is processed in plaintext. In other cases, a byte stream is used.

byte-based I/O operation interfaceOverview

BYTE-based I/O operation interface inputs and outputs are: InputStream and Outputstream,inputstream the class inheritance hierarchy for the input stream is as follows:

Figure 1. InputStream Related class hierarchies (view larger image)

The input stream is divided into sub-classes according to the data type and operation mode, each of which handles different operation types, and the class hierarchy of the OutputStream output stream is similar, as shown in:

Figure 2. OutputStream Related class hierarchies (view larger image)

Example 1: Reading and storing pictures using a byte stream

You first use the input stream to read the picture information, and then write the picture information through the output stream:

 PackageOrg.example.io;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream; Public  class testiostream {      /** * * DOC will be under the F-disk test.jpg file, read, and then save to the E-drive below. * * @param args * @throws Exception * *       Public Static void Main(string[] args)throwsException {FileInputStream in =NewFileInputStream (NewFile ("F:\\test.jpg"));//Specify the picture to be readFile File =NewFile ("E:\\test.jpg");if(!file.exists ()) {//If the file does not exist, the file is createdFile.createnewfile (); } FileOutputStream out =NewFileOutputStream (NewFile ("E:\\test.jpg"));//Specify the picture to write        intn =0;//bytes per read length        byte[] BB =New byte[1024x768];//store content for each read         while((n = in.read (BB))! =-1) {Out.write (BB,0, n);//Read content is written to the output stream} out.close ();//Close the input/output streamIn.close (); }  }
Example 2: Read and write pictures using Bufferedinputstream and Bufferedouputstream

The way of use is basically consistent with Fileinputstrem and FileOutputStream:

 PackageOrg.example.io;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream; Public classtestbufferedstring { Public Static voidMain (string[] args) throws Exception {//Specify the buffered input byte stream to read the fileBufferedinputstreaminch=NewBufferedinputstream (NewFileInputStream ("F:\\test.jpg")); File File =NewFile ("E:\\test.jpg");if(File! =NULL) {file.createnewfile (); }//Specifies the buffered output byte stream to write to the fileBufferedoutputstream out=NewBufferedoutputstream (NewFileOutputStream (file));byte[] BB =New byte[1024x768];//used to store each byte array read to        intNThe length of each byte array to read//         while((n =inch. Read (BB))! =-1) { out. Write (BB,0, n);//write to output stream} out. Close ();//Close stream        inch. Close (); }  }
character-based I/O operation interfaceOverview

Whether it's a disk or a network transmission, the smallest storage unit is bytes, not characters, so I/O operations are bytes instead of characters, but why are I/O interfaces that manipulate characters? This is because the data that we normally manipulate in our programs are in character form, and for the sake of convenience it is necessary to provide an I/O interface for direct write characters. We know that the character to byte must be encoded to be converted, and this code is very time-consuming, but also often garbled problems, so I/O coding problem is often a headache. For I/O coding issues, refer to another article, "in-depth analysis of the Chinese coding problem in Java."

The operator interface of the read character is also int read (char cbuf[], int off, int len), which returns the number of n bytes read, either writer or reader class, which defines only the way to read or write the data characters, that is, how to write or read, but there is no Where to write the data and where to write it is the disk-and network-based working mechanism that we'll discuss later

Figure 3. Reader class Hierarchy (view larger image)

is an I/O operation interface involving a class, the Writer class provides an abstract method of write (char cbuf[], int off, int len) to be implemented by subclasses.

Figure 4. Writer Related class hierarchy (view larger image)

Example 1: Use a character stream to read and store plain text files

Storing files, that is, writing content like a file, and since it is written, you need to use the output stream. And we're writing a plain text file, so here we use a character stream to manipulate it, and the Java API gives us filewriter such a class, let's try it: (read the file similarly using the FileReader class)

 PackageOrg.example.io;ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.IOException; Public  class testfilewriter {       Public Static void Main(string[] args)throwsException {writetofile ();      ReadFromFile (); }/** * DOC reads data from a file. * * @throws filenotfoundexception * @throws ioexception * *      Private Static void ReadFromFile()throwsFileNotFoundException, ioexception {File File =NewFile ("E:\\helloworld.txt");//Specify the files to readFileReader reader =NewFileReader (file);//Gets the input stream for the file        Char[] BB =New Char[1024x768];//used to save each read to the characterString str ="";//used to stitch each read to a character, of course using the StringBuffer class is better        intN//length of characters per read         while((n = reader.read (BB))! =-1) {str + =NewString (BB,0, n); } reader.close ();//close the input stream and release the connectionSystem.out.println (str); }/** * DOC writes data to the file. * * @throws ioexception * *      Private Static void WriteToFile()throwsIOException {String writercontent =Hello world.;//Text to be writtenFile File =NewFile ("E:\\helloworld.txt");//text file to be written        if(!file.exists ()) {//If the file does not exist, the file is createdFile.createnewfile (); } FileWriter writer =NewFileWriter (file);//Get the output stream of the fileWriter.write (writercontent);//write contentWriter.flush ();//Clears the buffer and writes the contents of the output stream to the file immediately .Writer.close ();//Close output stream, cast resource}  }

Test results:

Hello world.

Example 2: Read and write files through BufferedReader and BufferedWriter
 PackageOrg.example.io;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.IOException; Public  class testbufferedwriter {       Public Static void Main(string[] args)throwsException {write ();      Read (); }/** * DOC reads information. * * @throws filenotfoundexception * @throws ioexception * *      Private Static void Read()throwsFileNotFoundException, ioexception {File File =NewFile ("E:\\a.txt");//Specify the files to read        //Get buffered input stream for this fileBufferedReader BufferedReader =NewBufferedReader (NewFileReader (file)); String line ="";//Used to save the contents of each row read         while(line = Bufferedreader.readline ())! =NULL) {System.out.println (line); } bufferedreader.close ();//Close input stream}/** * DOC writes information. * * @throws ioexception * *      Private Static void Write()throwsIOException {File File =NewFile ("E:\\a.txt");//Specify the file to be written        if(!file.exists ()) {//If the file does not exist, createFile.createnewfile (); }//Gets the buffered output stream of the fileBufferedWriter BufferedWriter =NewBufferedWriter (NewFileWriter (file));//write informationBufferedwriter.write ("Hello World"); Bufferedwriter.newline ();//= line breakBufferedwriter.write ("Hello World"); Bufferedwriter.flush ();//Clear bufferBufferedwriter.close ();//Close output stream}  }
byte-to-character conversion interfaceOverview

In addition, data persistence or network transmission is done in bytes, so there must be a conversion of characters to bytes or bytes to characters. The character to byte needs to be converted, where the read conversion process is as shown:

The InputStreamReader class is a byte-to-character conversion bridge, and the process of InputStream to Reader specifies the encoding character set, otherwise the operating system default character set is used, and garbled issues are likely to occur. Streamdecoder is the implementation class that completes the decoding of byte-to-character. That is, when you read a file in the following way:

try {             strnew StringBuffer();             charnewchar[1024];             new FileReader("file");             while(f.read(buf)>0){                 str.append(buf);             }             str.toString();  catch (IOException e) {}

FileReader class is to read the file according to the above work, FileReader is inherited InputStreamReader class, is actually read the file stream, and then decoded by Streamdecoder to Char, Only the decoded character set here is the default character set.

Writing is also similar to the process as shown in:

Through the OutputStreamWriter class, the character-to-byte encoding process is completed by the Streamencoder encoding process.

Example: using the transform stream inputstreamreader and OutputStreamWriter

The conversion flow is required when converting between a byte stream and a character stream, or when you want to encode bytes of data

 PackageOrg.example.io;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter; Public classTeststreamreader { Public Static voidMain (string[] args) throws Exception {File File =NewFile ("E:\\b.txt");if(!file.exists ())          {File.createnewfile (); } outputstreamwriter out=NewOutputStreamWriter (NewFileOutputStream (file),"GBK"); out. Write (Hello world.); out. Close (); InputStreamReaderinch=NewInputStreamReader (NewFileInputStream (file),"GBK");Char[] cc =New Char[1024x768];intn =0; String str =""; while((n =inch. Read (CC))! =-1) {str + =NewString (CC,0, n); }inch. Close (); System. out. println (str); }  }
Reference

In-depth analysis of how Java I/O works:
https://www.ibm.com/developerworks/cn/java/j-lo-javaio/

In-depth analysis of Chinese coding problems in Java
http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/

Java IO stream
http://blog.csdn.net/a107494639/article/details/7586365

Java-based file IO

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.