JAVA input/output stream Summary

Source: Internet
Author: User

 

We all know that there are three ways to store data on a computer: External Storage, memory, and cache. For example, hard disks, disks, and USB flash drives on a computer are all stored externally. Memory is stored on the computer and cached on the CPU. External Storage has the largest storage capacity, followed by memory, and finally cache. However, external storage reads the slowest data, followed by memory, and the fastest cache. Here we will summarize how to read data from external memory to memory and write data from memory to external memory. For memory and external storage, we can simply understand it as a container, that is, external storage is a container, and memory is another container. Then, how can we read the data stored in the external storage container to the memory container and how can we store the data in the memory container to the external storage? The input and output classes are provided in Java. In the java. io package, the input and output abstraction is called a stream in java. It is like a pipe that connects two containers. The input stream is used to read data from the external store to the memory, and the output stream is used to write data from the memory to the external store. The following uses the file input stream and file output stream as examples to describe how to read and write data.

According to the API documentation, the file input stream FileInputStream has only one constructor FilterInputStream (InputStream in), which passes in an InputStream type parameter. Once you know the constructor method, You Can instantiate a FileInputStream class object. To read data from the hard disk to the memory, first define a FileTest class, then define a method readFile (), and input a string parameter for the method to read a file path, returns a string value. First, a FileInputStream class object is required in the method. Therefore, you need to instantiate a FileInputStream Class Object: java. io. fileInputStream FCM = new java. io. fileInputStream (path); An Exception error will be prompted when the object is instantiated. Here we will not discuss the Exception mechanism, just in a fixed format: try {} catch (Exception ct) {ct. printStackTrace. After creating an object, you can use this class to read data. First, you must read the length of the file. You can use the available () method to read the data in the file. You can use the read () method to read data in only one byte and one byte. Finally, we need to instantiate a byte array. Its function is to save the read data to the array. We also need a whlie loop to read all the data into the array, note that the read () method returns-1 when the last byte is read. Do not forget to close the input stream by using the close () method after reading it. The Code is as follows:

/**

* Read the data of the file in the specified path.

* @ Param path: the specified path.

* @ Return: returns string-type data.

*/

Public String readFile (String path ){

 

Try {

// Create a file input stream object

Java. io. FileInputStream FCM = new java. io. FileInputStream (path );

 

// Obtain the object Length

Int len = FCM. available ();

 

// Create a byte array based on the file length to save the data read from the file

Byte [] bt = new byte [len];

 

 

// Read a byte

Int bj = FCM. read ();

Int I = 0;

While (bj! =-1 ){

// Put the read bytes into the Array

Bt [I] = (byte) bj;

// Continue reading the next byte

Bj = FCM. read ();

I ++;

 

}

 

The method for writing data from the memory to the specified file in the external store is similar to the above method. The corresponding FileOutputStream class has five constructor methods. Here we use the FileOutputStream (String name) constructor to instantiate an object. First, define a writeFile () method, and then pass in the specified file path and two string parameters of the data to be written. Then instantiate a java. io. FileOutputStream fs = new java. io. FileOutputStream (path). An Exception error will also be reported in the same way as above. The handling method is the same as above. Before writing a String, convert the String to a byte array. In the String class, there is a method getBytes ()

Converts a string to a byte array. Then we need to traverse the byte array and write each element in the byte array in sequence. Finally, do not forget to use the fs. flush (); and fs. close () Methods to forcibly output and disable the output streams respectively. The Code is as follows:

/**

* Write data to a specified file

* @ Param path: Specifies the file

* @ Param content: written data

*/

Public void writeFile (String path, String content ){

 

Try {

// Create an output stream object

Java. io. FileOutputStream fs = new java. io. FileOutputStream (path );

 

// Convert the string into a byte array

Byte [] B = content. getBytes ();

 

// Traverse the Array

For (int I = 0; I <B. length; I ++ ){

// Write data

Fs. write (B [I]);

}

// Force write all bytes in the output stream

Fs. flush ();

 

// Close the stream

Fs. close ();

 

} Catch (Exception et ){

Et. printStackTrace ();

}

 

}

After writing the preceding two methods, you can call the first method and then call the second method to copy the file. However, there are two problems with this replication. The first is that the replication speed is too slow, and the second is that some files are garbled after replication and cannot be viewed. To solve these two problems, we must first analyze the execution process of the above two methods. We can see that the first method uses an array, and the second method converts the string to a byte array. Therefore, consider not using arrays, and do not convert strings into byte arrays. Therefore, we need to read data while writing data. This not only solves the first two problems, but also simplifies the code. The specific code is as follows:

/**

* File replication method

* @ Param srcPath

* @ Param destPath

* @ Return

*/

Public boolean copyFile (String srcPath, String destPath ){

 

Try {

// Create an input stream object

Java. io. FileInputStream FCM = new java. io. FileInputStream (srcPath );

// Create an output stream object

Java. io. FileOutputStream fos = new java. io. FileOutputStream (destPath );

 

// Read one byte of data

Int rd = FCM. read ();

 

While (rd! =-1 ){

 

// Write the data in the memory to the hard disk file

Fos. write (rd );

 

// Continue reading data

Rd = FCM. read ();

 

}

 

// Close the input stream

FCM. close ();

 

// Force write the remaining data in the output stream

Fos. flush ();

 

// Close the output stream

Fos. close ();

 

Return true;

 

} Catch (Exception ct ){

Ct. printStackTrace ();

}

 

Return false;

}

 

After the above Code is modified, there is basically no problem in copying files. However, when copying large files, the speed is still very slow. In this case, you need to input and output the buffer stream, they are BufferedInputStream and BufferedOutputStream.

Their usage is as follows:

/**

* File replication method

*

* @ Param srcPath

* @ Param destPath

* @ Return

*/

Public boolean copyFile (String srcPath, String destPath ){

 

Try {

// Create an input stream object

Java. io. FileInputStream FCM = new java. io. FileInputStream (srcPath );

// Create an output stream object

Java. io. FileOutputStream fos = new java. io. FileOutputStream (destPath );

 

// Create an input buffer stream

Java. io. BufferedInputStream bis = new java. io. BufferedInputStream (FCM );

 

// Create an output buffer stream

Java. io. BufferedOutputStream bos = new java. io. BufferedOutputStream (fos );

 

// Read one byte of data

Int rd = bis. read ();

 

While (rd! =-1 ){

 

// Write the data in the memory to the hard disk file

Bos. write (rd );

 

// Continue reading data

Rd = bis. read ();

 

}

 

// Close the input stream

FCM. close ();

 

// Force write the remaining data in the output stream

Fos. flush ();

 

// Close the output stream

Fos. close ();

 

Return true;

 

} Catch (Exception ct ){

Ct. printStackTrace ();

}

 

Return false;

}

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.