S2/java/10-file I/O

Source: Internet
Author: User

The Java.io package provides interfaces and classes to perform basic operations on files, including operations on file and directory attributes, operations on file reads and writes, and so on.

The file object can represent files or directories.

The syntax format for creating a file object is as follows:

File File=new file (String pathName);

Where pathname represents the path name of the file to which it is pointing.

For example, "File File=new file (" C:\\Test.txt "); Created an object that points to the Test.txt text file under the C packing directory.

Note that in the Windows operating system, the delimiter in the file pathname can use a forward slash "/", such as "c:/test.txt" or a backslash "\", but must be written as "\ \" where the first one represents an escape character, such as "C:\\Test.txt".

The file object is the only object in the Java.io package that references the disk file. The file class simply describes the properties of the file object and does not describe how the data is stored. The file class provides some important ways to manage the properties of files or directories, as shown in the following table:

Common methods for file classes

Method name

Description

Boolean exists ()

Determine if a file or directory exists

Boolean isfile ()

Determine if it is a file

Boolean isdirectory ()

Determine if it is a directory

String GetPath ()

Returns the relative path name of the file represented by this object

String GetAbsolutePath ()

Returns the absolute path name of the file represented by this object

String GetName ()

Returns the name of the file or directory represented by this object

Boolean Delete ()

Delete the file or directory specified by this object

Boolean CreateNewFile ()

Create an empty file with a name and do not create a folder

Long Length ()

Returns the length of the file, in bytes, or 0L if the file does not exist

Reading a file refers to reading the data in the file into memory. Conversely, writes the data in memory to the file when the file is written. The stream to read and write files, streams, refers to a series of flowing characters, is the first-in-one way to send and receive data channels.

When writing data to a stream, this stream is called the output stream, and the output stream can send information to the outside of the program. Data can be read from an output stream.

In the Java.io package, the API for many input/output streams is encapsulated. In programs, the objects of these input/output stream classes are called Stream objects. These stream objects can be used to stream in-memory data to a file, or stream objects to read the data in the file to memory in a streaming manner.

Stream objects are often constructed with data sources (such as files) associated with them. The data source is divided into the source data source and the target data source. The input stream is contacted by the source data source, and the output stream is associated with the destination data source.

(1) According to different classification methods, the flow can be divided into different types.

1. Input stream: Data can only be read from and not written to.

2. Output stream: Data can only be written to, not read from.

For example, data from memory to hard disk, usually we call the output stream. In other words, the input and output here are divided from the memory angle in which the program is running.

The output stream of Java mainly consists of OutputStream and writer as the base class, while the input stream is mainly composed of inputstream and reader as base class.

(2) According to the data unit of the operation, the stream can be divided into a byte stream and a character stream.

The minimum data unit for a byte stream operation is 8 bytes, while the minimum data unit of a character stream operation is a 16-bit character.

The distinction between a byte stream and a character stream is very simple, the byte stream is recommended for binary data (slices), and the character stream is used for text, and their usage is almost identical.

According to the flow direction, we can also continue to divide the byte stream and the character stream, to separate bytes input stream, byte output stream, character input stream, character output stream.

    • Byte input stream InputStream class

The function of byte input stream InputStream is to input the data in the file into internal memory (called memory), which provides a series of methods related to reading data, the common method is as follows:

Common ways to read data

Method name

Description

int read ()

Read a byte of data

int read (byte[] b)

Reading data into a byte array

int read (byte[] b,int off,int len)

Reads bytes up to Len length from the input stream, saved in byte array B, and the saved position starts from off

void Close ()

Close the input stream

int available

Returns the estimated number of bytes read by the input stream

The non-parametric read () method reads a 8-bit byte from the input stream, converting it to an integer returned between 0~255.

The two read () method with the parameter reads a number of bytes from the input stream in bulk. When reading data from a file or keyboard, using read (byte[] b) or read (byte[] b,int off,int len) method can reduce the number of physical read files or keyboards, and improve the efficiency of input/output operations.

    • Direct input stream FileInputStream class

In the practical application, we usually use the subclass FileInputStream class of InputStream to realize the reading of the content of the text file, the common construction method has the following two.

1, fileinputstream (file file).

Where file specifies the data source for the files. Use this construction method to create a file input stream object as follows.

File File=new file ("C:\\Test.txt");

InputStream fileobject=new fileinputstream (file);

At this point, the file input stream object FileObject is associated with the source data source (c:\\test.txt file).

2, FileInputStream (String name).

Where name specifies the file data source, which contains the path information. Use this construction method to create a file input stream object as follows.

(File) InputStream in=new FileInputStream ("C:\\Test.txt");

3. Use FileInputStream to read the text file using the following steps.

(1) Introduce the relevant classes.

Import java.io.IOException;

Import Java.io.InputStream;

Import Java.io.FileInputStream;

(2) Create a file input stream object.

InputStream fileobject=new FileInputStream ("C:\\Test.txt");

(3) Use the file input stream method to read the text file data.

Fileobejct.available (); Number of bytes that can be read

Fileobject.read (); Reading data from a file

(4) Close the file input stream object.

Fileobject.close ()

There are a few things you should be aware of when reading file data using the FileInputStream class.

(1) The Read () method returns an integer and, if the string is being read, the type conversion is enforced. For example, if the idea is to output "ABC" correctly, the output statement needs to be modified to "System.out.print ((char) data+" ");".

(2) The stream object needs to be closed when it is finished.

10.3.2 writing a text file using a byte stream

1, byte output stream OutputStream class

The function of byte output stream OutputStream is to output the in-memory data to a file, which provides a series of methods to write data to the file, the common method is as follows.

Common methods of OutputStream class

Method name

Description

void write (int c)

Write a byte of data

void Write (byte[] buf)

Writes all bytes of the array buf

void Write (byte[] b,int off,int len)

Starts from the off position in the byte array, and Len-length bytes data is output to the output stream

void Close ()

Turn off the output stream

2, byte output stream FileOutputStream class

In practical applications, we usually use the subclass FileOutputStream class of OutputStream to implement writing data to a text file, and there are 3 common methods of constructing it.

(1) FileOutputStream (file file).

Where file specifies the destination data source. Use this construction method to create a file output stream object as follows.

File File=new file ("C:\\Test.txt");

FileOutputStream fos=new fileoutputstream (file);

At this point the file output stream object FOS is associated with the target data source (c:\\test.txt file).

(2) FileOutputStream (String name).

Where name specifies the file destination data source, which contains the path information. Use this construction method to create a file output stream object as follows.

FileOutputStream fos=new FileOutputStream ("C:\\Test.txt");

(3) FileOutputStream (String name,boolean append).

Where name specifies the file destination data source, which contains the path information. Append indicates whether data is added at the end of the file and, if set to true, adds data at the end of the file. Use this construction method to create a file output stream object as follows.

FileOutputStream fos=new FileOutputStream ("C:\\Test.txt", true);

It is important to note that the first and second construction methods overwrite the contents of the file when writing data to the file. In addition, when you create an FileOutputStream instance using FileOutputStream's construction method, an empty file is created automatically if the corresponding file does not exist. If the file path represented by the parameter file or name exists, but represents a file directory, this time the FileNotFoundException exception is thrown.

3. Write text files using FileOutputStream

Use FileOutputStream to write data to a text file using the following steps.

(1) Introduce the relevant classes.

Import java.io.IOException;

Import Java.io.OutputStream;

Import Java.io.FileOutputStream;

(2) Constructs a file output stream object.

OutputStream fos=new FileOutputStream ("C:\\Test.txt");

(3) Use the file output stream method to write data to a text file.

String str= "Learning java Well";

Byte[] Words=str.getbyte ();

Write data to a file using the Write method

Fos.write (word,0,words.length);

(4) Close the file output stream.

Fos.close ();

Note: First the string to be written to the file is converted to byte array words through the GetByte () method, then the write () method of the output stream object is called, and the contents of the byte array words are added to the end of the file as C:\myDoc\hello.txt.

10.3.4 reading a text file using a character stream

1. Character input stream Reader class

The reader class is an abstract class that reads a stream of characters, and it provides a common method

Common methods of Reader class

Method name

Description

int read ()

Reading a single character from the input stream

int read (byte[] c)

Reads C.length-length characters from the input stream, saves to character array C, returns the number of characters actually read

Read (char[] c,int off,int len)

A length character that reads up to Len from the input stream, is saved to the character array C, and the saved position starts at the off position, returning the actual length of the character read

void Close ()

Close the stream

2. Character input stream FileReader class

The FileReader class is a subclass of reader and is commonly used in the following form of construction methods.

FileReader (String fileName)

where filename refers to the name of the file from which to read the data. Use this construction method to create a character input stream object as follows.

Reader fr=new FileReader ("C:\\mytest.txt");

3. read files using FileReader

The following steps are used to read a text file using the character stream class FileReader.

(1) Introduce the relevant classes.

Import Java.io.Reader;

Import Java.io.FileReader;

Import java.io.IOException;

(2) Create a FileReader object.

Reader fr=new FileReader ("C:\\mytest.txt");

(3) Use the FileReader class method to read the data of the text file.

int read (); Reading a single character

(4) Closes the associated stream object.

Fr.close ();

4. Character input stream Bufferreader class

The Bufferreader class is a subclass of the reader class, and the main difference between him and the FileReader class is that the Bufferreader class has a buffer, which can read a batch of data to the buffer, and the next read operation is to fetch the data from the buffer. Avoid reading data from the data source every time for character encoding conversion, thus improving the efficiency of the read operation. The common construction methods of the Bufferreader class are as follows.

Bufferreader (Reader in)

Use this construction method to create a character input object as follows.

Reader fr=new FileReader ("C:\\mytest.txt");

Bufferreader br=new Bufferreader (FR);

Where BR is a buffered character input stream that is created using the default size input buffer.

5. Use FileReader and Bufferreader to read text files

The following steps are used to read a text file using the character stream class Bufferreader and FileReader.

(1) Introduce the relevant classes.

Import Java.io.FileReader;

Import Java.io.BufferReader;

Import java.io.IOException;

(2) Create a Bufferreader object.

Reader fr=new FileReader ("C:\\mytest.txt");

Bufferreader br=new Bufferreader (FR);

(3) Use the Bufferreader class method to read the data of the text file.

Br.readline (); Reads a row of data, returns a string

(4) Closes the associated stream object.

Br.close ();

Fr.close ();

10.3.5 writing a text file using a character stream

1. Character output stream writer class

The writer class is a stream of characters that writes data to a file, which provides a common method

Common methods of writer class

Method name

Description

Write (String str)

Outputs the characters contained in the STR string to the specified output stream

Write (String str,int off,int len)

Outputs a character from the off position of the STR string to the output stream, starting with the length Len

void Close ()

Turn off the output stream

void Fulsh ()

Refresh the output stream

2, character output stream FileWriter class

The FileWriter class is a subclass of writer, and the commonly used method of constructing the format is as follows.

FileWriter (String fileName)

where filename represents the system-related file name, using this construction method to create a character output stream object as follows.

Writer fr=new FileWriter ("C:\\mytestr.txt");

3. Write text files using FileWriter

Use the character stream class FileWriter to write data to a text file in the following steps:

(1) Introduce the relevant classes.

Import Java.io.FileWriter;

Import java.io.IOException;

(2) Create a FileWriter object.

Writer fw=new FileWriter ("C:\\mytest.txt");

(3) Write a text file using the FileWriter class method.

Fw.write ("Hello");

(4) emptying and closing of related stream objects.

Fw.flush (); Refreshes the buffer of the stream

Fw.close (); Close this stream

4. Character input stream BufferedWriter class

BufferedWriter is the subclass of writer. BufferedWriter and BufferedReader flow in the opposite direction, BufferedWriter is to write a batch of data into the buffer, when the buffer is full, and then write the buffer data into the character output stream. This avoids performing physical writes every time, thereby increasing the efficiency of the input/output operation. The common construction methods of the BufferedWriter class are as follows.

BufferedWriter (Writer out)

Use this construction method to create a character output stream object as follows.

Writer fw=new FileWriter ("C:\\mytest.txt");

BufferedWriter bw=new BufferedWriter (FW);

Where bw is created using the default size output buffer character output stream.

5. Write text files using BufferedWriter and FileWriter

Use the character stream class BufferedWriter and FileWriter to write data to a text file in the following steps:

(1) Introduce the relevant classes.

Import Java.io.FileWriter;

Import Java.io.BufferedWriter;

Import java.io.IOException;

(2) Constructs a BufferedWriter object.

FileWriter fw=new FileWriter ("C:\\mytest.txt");

BufferedWriter bw=new BufferedWriter (FW);

(3) Write a text file using the BufferedWriter class method.

Bw.write ("Hello");

(4) The clear sky and close of the related flow object.

Bw.flush (); Refreshes the buffer of the stream

Fw.close (); Close this stream

Attention:

In the example, "Bw.newline ()" is used, and the NewLine () method is a method in the BufferedWriter class that inserts a newline character.

There is a difference between the byte stream and the character stream in the operation, and the character stream uses the buffer (internal memory) when it is operated, and the byte stream is manipulated directly by the file and is not used in the buffer.

10.4.1 using the byte stream class DataInputStream read the binary file

The DataInputStream class is a subclass of FileInputStream, which is an extension of the FileInputStream class. The implementation of using the DataInputStream class to read a binary file is very similar to the steps for reading a text file using the FileInputStream class, and also to the FileInputStream class.

The following steps are described.

(1) Introduce the relevant classes.

Import Java.io.FileInputStream;

Import Java.io.DataInputStream;

(2) Constructs a data input stream object.

FileInputStream fis=new FileInputStream ("C:\\helloword.class");

DataInputStream dis=new datainputstream (FIS);

(3) The data input stream class is used to read the data of the binary file.

Dis.read (); Read data bytes

(4) Close the data input stream.

Dis.close (); Turn off the data entry stream

10.4.2 using the byte stream class DataOutputStream to write the binary file

The DataOutputStream class is a subclass of FileOutputStream, which is an extension of the FileOutputStream class. The implementation of using the DataOutputStream class to write a binary file is very similar to the procedure for writing a text file using the FileOutputStream class, and it also uses the FileOutputStream class. The following steps are described.

(1) Introduce the relevant classes.

Import Java.io.FileOutputStream;

Import Java.io.DataOutputStream;

(2) Constructs a data output stream object.

FileOutputStream outfile=new FileOutputStream ("C:\\temp.class");

DataOutputStream out=new DataOutputStream (outFile);

(3) using the data output stream class method to write binary data.

Out.write (1); Writes the specified byte data to a binary file

(4) Turn off the data output stream.

Out.close ();

Information:

The DataInputStream class is used in conjunction with the DataOutputStream class to read data from a stream in a platform-independent way, such as int, float, long, double, and Boolean. In addition, DataInputStream's readUTF () method can read strings encoded with utf-8 characters.

The key code is shown below.

FileOutputStream out1=new FileOutputStream ("D:\\mydoc\\hello.txt");

Bufferedoutputstream out2=new Bufferedoutputstream (OUT1);

DataOutputStream out=new DataOutputStream (OUT2);

Out.writebyte (1);

Out.writelong (2);

Out.writechar (' C ');

Out.writeutf ("Hello");

The DataOutputStream class can write data of the base data type to the stream in a platform-independent manner, such as int, float, long, double, and Boolean. In addition, the DataOutputStream writeUTF () method can write to strings that are encoded with UTF-8 characters.

Some methods of the DataOutputStream class are those that start with write, such as WriteByte (), Writelong (), and so on.

The key code is shown below.

FileInputStream in1=new FileInputStream ("D:\\mydoc\\hello.txt");

Bufferedinputstream in2=new Bufferedinputstream (in1);

DataInputStream in=new DataInputStream (in2);

System.out.println (In.readbyte ());

System.out.println (In.readlong ());

System.out.println (In.readchar ());

System.out.println (In.readutf ());

S2/java/10-file I/O

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.