Java (5)-Java I/O technology, java (advanced)

Source: Internet
Author: User

Java (5)-Java I/O technology, java (advanced)

In the program, in order to permanently Save the created data, you need to save it in the disk file so that they can be used in other programs. Java I/O technology can save data to text files, binary files, and even ZIP compressed files to meet the requirement of permanent data storage.

In this article, we will introduce Java I/O technology, that is, input/output.

I. Input/output streams

A stream is a set of ordered data sequences. It can be divided into input streams and output streams based on the operation type.

Classes responsible for input and output in various ways are put in java. io packages. All input streams are subclasses of the abstract class InputStream (byte input stream) or the abstract class Reader (character input stream); all output streams are abstract class OutputStream (byte output stream) or abstract class Writer (character output stream).

1. byte input/output stream

The following is an example of a byte input/output stream. Among them, the 14th behavior reads bytes from the input stream and stores them in the buffer array. The maximum length is 2500 bytes, And the return value B is the actual read length.

1 import java. io. file; 2 import java. io. fileInputStream; 3 import java. io. fileOutputStream; 4 5 public class IOExample {6 public static void main (String [] args) {7 try {8 int B; 9 File file = new File ("E: \ test.txt "); // create a file 10 11 FileInputStream readfile = new FileInputStream (file); // create an input stream 12 13 byte buffer [] = new byte [2500]; // create a byte array 14 B = readfile. read (buffer, 1, 2000); // 1 is the starting offset of 15 String str = new String (buffer, 0, B, "Default") in the buffer array; 16 System. out. println (str); 17 readfile. close (); // close stream 18 19 FileOutputStream writefile = new FileOutputStream (file, true); // create an output stream. true indicates that the original data is retained, append new data to the end of 20 writefile. write (buffer, 0, B); 21 writefile. close (); 22} catch (Exception e) {23 e. printStackTrace (); 24} 25} 26}

The FileInputStream class and FileOutputStream class in the above Code belong to the file input and output stream, which are inherited from the InputStream class and OutputStream class respectively.

Common InputStream methods include read (), close (), and reset (). Common Methods of OutputStream include write (), flush (), and close. For details, refer to the API.

2. Character Input/output stream

The following is an example of a character input/output stream.

1 import java. io. fileReader; 2 import java. io. fileWriter; 3 4 public class IOExample {5 public static void main (String [] args) {6 try {7 FileReader fileread = new FileReader ("E: \ test.txt "); // character input stream, Read File Information 8 9 char [] cbuf = new char [500]; 10 int B = fileread. read (cbuf, 0,500); 11 System. out. println (String. valueOf (cbuf); 12 fileread. close (); 13 14 FileWriter filewriter = new FileWriter ("E: \ test.txt", true); // character output stream, which writes information to the output stream, and keep the original data. append the data value to 15 filewriter at the end. write (cbuf); 16 filewriter. close (); 17} catch (Exception e) {18 e. printStackTrace (); 19} 20} 21}

The FileReader class and FileWriter class in the above Code also belong to the file input and output stream.

3. file input/output stream

The above code shows a new term called file input/output stream, that is, FileInputStream, FileOutputStream, FileReader, and FileWriter. They are used to establish a connection with the specified file and permanently Save the required data to the file.

FileInputStream and FileOutputStream are both used to operate disk files. This class can be used if the user's file reading is relatively simple. However, because Chinese characters occupy two bytes in the file, garbled characters may occur if reading is poor.

FileReader class and FileWriter class can avoid garbled characters, which correspond to the FileInputStream class and FileOutputStream class respectively.

Ii. File

The File class is the only object in the io package that represents the disk File itself. You can create, delete, and rename files by calling the methods in the File class.

1. File Creation and Deletion

You can use the File class to create a File object. The syntax format of the three constructor methods is as follows:

new File(String pathname)new File(String parent, String child)new File(File f, String child)

Pathname is the path name, parent is the parent path string, child is the sub-path string, and f is the parent path object. For example:

File file = new File("E:/test.txt");File file = new File("E:/myword","word.txt");

If no file named wordexists in the E:/myworddirectory, you can create a file named word.txt through createnewfile(folder names). If yes, you can delete it by using the delete () method.

2. Get File Information

The File class provides many methods to obtain information about the File itself. The following table lists some common methods.

Method Description
GetName () Get File Name
CanRead () Determine whether the file is readable
CanWrite () Determine whether a file can be written
Exist () Determine whether a file exists
Length () Get the object Length
GetAbsolutePath () Obtain the absolute path of a file
GetParent () Obtain the parent path of an object
IsFile () Determine whether a file exists
IsDirectory () Determine whether the file is a directory
IsHidden () Determine whether the object is a hidden object
LastModifed () Obtain the last file modification time

For example, we create an object and obtain the object length information as follows:

1 import java. io. file; 2 3 public class FileTest {4 5 public static void main (String [] args) {6 File file = new File ("E:/myword", "word.txt "); // create a file object 7 if (file. exists () {// checks whether the file exists 8 String name = file. getName (); // get the object name 9 long length = file. length (); // get the object length 10 boolean hidden = file. isHidden (); // checks whether the file is a hidden file 11 12 System. out. println ("file name:" + name); 13 System. out. println ("file length:" + length); 14 System. out. println ("Whether the file is hidden:" + hidden); 15} else {16 System. out. println ("file does not exist"); 17} 18} 19 20}
3. Input/output stream with Cache

Cache is an I/O performance optimization. The cache stream adds a memory cache area for the I/O Stream.

1. BufferedInputStream and BufferedOutoutStream

The constructor is as follows:

BufferedInputStream(InputStream in)BufferedInputStream(InputStream in, int size)BufferedOutputStream(OutputStream in)BufferedOutputStream(OutputStream in, int size)
2. BufferedReader and BufferedWriter

The common method is as follows:

Method Description
Read () Read a single character
ReadLine () Reads a text line and returns a string. If no data exists, returns null.
Write (String s, int off, int len) Write a part of a string
Flush () Refresh the cache of the stream
NewLine () Write a row Separator

Note that when using the write () method of the BufferedWriter class, the data is not immediately written to the output stream, but first enters the cache area, to immediately write data in the buffer to the output stream, you must call the flush () method.

Iv. Data Input/output stream

The data input/output stream is a DataInputStream class and a DateOutputStream class, allowing applications to read Basic Java data types from the underlying input stream in a machine-independent manner.

The constructor is as follows:

DataInputStream(InputStream in)DataOutputStream(OutputStream out)

The DataOutputStream class provides the following three methods for writing strings:

writeBytes(String s)writeChars(String s)writeUTF(String s)
5. ZIP compression of input/output streams

The zipoutputstreamclass object can be used to compress the file into a. ZIP file.

The constructor is as follows:

ZipOutputStream(OutputStream out);

The ZipInputStream class can read files in ZIP compression format, including support for compressed and uncompressed entries.

The constructor is as follows:

ZipInputStream(InputStream out);

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.