Fileinputstream/fileoutputstream Application

Source: Internet
Author: User

This is a pair of classes inherited from inputstream and outputstream, used for local file read/write (binary format read/write and sequential read/write, read and write respectively to create different file stream objects );

The basic process of local file read/write programming is:

① Generate a file stream object (fileinputstream class should be used for file read operations, and fileoutputstream class should be used for file write );

② Call functions in the fileinputstream or fileoutputstream class, such as read () and write (INT B), to read and write the file content;

③ Close ()).

Instance: stream file read/write

The unit of a stream file is byte, so it can not only read and write text files, but also read and write images, sounds, and image files. This feature is very useful because we can convert this file into a stream, and then transmitted over the network.

The problem is, after a common stream file is available, why do we need a dedicated stream? This is because the text can be stored in different ways, can be a common text (UTF-8 encoding), ASCII text and Unicode text, pipeline flow object can be converted as necessary, to read the correct text.

Some people think that stream files cannot read or write text files. This is a misunderstanding, because text files are essentially composed of bytes, of course, a stream file. It is okay to read and write the entire file. However, if you want to process the content read each time, you 'd better use the volume stream.

Therefore, stream processing is the most common method for text file processing.

Example:

Import java. Io .*;

Public class filestreamdemo {

Public static void main (string [] ARGs) throws ioexception {

// Create two files. face.gif is the existing file, and newface.gif is the newly created file.

File infile = new file ("face.gif ");

File OUTFILE = new file ("newface.gif ");

// Create a stream File Reading and Writing Class

Fileinputstream instream = new fileinputstream (infile );

Fileoutputstream outstream = new fileoutputstream (OUTFILE );

// Use the available method to obtain the maximum number of characters in a stream.

Byte [] inoutb = new byte [instream. Available ()];

Instream. Read (inoutb); // read to the stream and save it in the byte array

Outstream. Write (inoutb); // write stream, which is stored in newface.gif

Instream. Close ();

Outstream. Close ();

}

}

Example: read and write any large file application

Because the maximum storage value of the byte array cannot exceed 64 MB, when a file is larger than 60 MB, several stream operations need to be separated. We can modify the above program to write any size of files. This program applies the fileinputstream class method as follows:

Read (byte [] B, int off, int Len)

Read the stream content at a specific position into the array. The content that has been read into the byte [] array will be deleted from the stream file.

The result of running the program will generate a new file.

Example:

Import java. Io .*;

Public class filestreamdemo2 {

Public static void main (string [] ARGs) throws ioexception {

// Create two files

File infile = new file ("tcty36.rm ");

File OUTFILE = new file ("newtcty36.rm ");

// The maximum stream size is 60 MB. When the file size is greater than 60 MB, the stream is split.

Final int max_byte = 60000000;

Long streamtotal = 0; // accept the stream capacity

Int streamnum = 0; // Number of streams to be separated

Int leave = 0; // number of remaining characters in the file

Byte [] inoutb; // The byte array accepts the file data

// Create a stream File Reading and Writing Class

Fileinputstream instream = new fileinputstream (infile );

Fileoutputstream outstream = new fileoutputstream (OUTFILE );

// Use the available method to obtain the maximum number of characters in a stream.

Streamtotal = instream. Available ();

// Number of Stream files to be separated

Streamnum = (INT) math. Floor (streamtotal/max_byte );

// Number of files remaining after separation

Leave = (INT) streamtotal % max_byte;

// When the file capacity is greater than 60 MB

If (streamnum> 0 ){

For (INT I = 0; I <streamnum; ++ I ){

Inoutb = new byte [max_byte];

// Read the stream and save it in the byte array

Instream. Read (inoutb, 0, max_byte );

Outstream. Write (inoutb); // write the stream

Outstream. Flush (); // update the written result

}

}

// Write the remaining Stream Data

Inoutb = new byte [leave];

Instream. Read (inoutb, 0, leave );

Outstream. Write (inoutb );

Outstream. Flush ();

Instream. Close ();

Outstream. Close ();

}

}

6. Pipeline pipedinputstream/pipedoutputstream class:

When you need to read and write data in two threads, the synchronization of read and write may be difficult due to concurrent execution of the thread. At this time, you can use pipelines, which are actually a queue.

Pipeline is a buffer maintained by the system. Of course, programmers can also directly specify the buffer size (only the value of the pipe_size attribute in the pipeline stream class needs to be set ). After the producer generates data, it only needs to write the data to the MPs queue, and the consumer only needs to read the required data from the MPs queue. Using this mechanism of pipelines, the output results of one thread can be directly connected to the input port of another thread to realize direct data transfer between the two.

Thread 1
Thread 2
Temporary Files
MPs queue

1. Pipeline Connection:

One method is to directly use the output of a program as the input of another program through the constructor, and specify the target pipeline object when defining the object.

Pipedinputstream pinput = new pipedinputstream ();

Pipedoutputstream poutput = new pipedoutputstream (pinput );

The second method is to connect using any member function connect () in both classes.

Pipedinputstream pinput = new pipedinputstream ();

Pipedoutputstream poutput = new pipedoutputstream ();

Pinput. Connect (poutput );

2. MPS queue input and output:

The output pipeline object calls the write () member function to output data (that is, send data to the input of the pipeline), and the input pipeline object calls read () member functions can read data (that is, obtain data from the output pipeline ). This is mainly achieved through the system's buffer mechanism.

Example: Java pipeline Input and Output

Import java. Io .*;

Public class pipedio // copy the content of sendfile to the receiverfile after the program runs.

{

Public static void main (string ARGs [])

{

Try

{

// Construct a read/write pipeline Stream Object

Pipedinputstream Pis = new pipedinputstream ();

Pipedoutputstream Pos = new pipedoutputstream ();

// Implement Association

POs. Connect (PIS );

// Construct two threads and start them.

New sender (Pos, "C: \ text2.txt"). Start ();

New Explorer (PIs, "C: \ text3.txt"). Start ();

}

Catch (ioexception E)

{

System. Out. println ("pipe error" + E );

}

}

}

// Thread sending

Class sender extends thread

{

Pipedoutputstream Pos;

File file;

// Constructor

Sender (pipedoutputstream POs, string filename)

{

This. Pos = Pos;

File = new file (filename );

}

// Thread running Method

Public void run ()

{

Try

{

// Read the file content

Fileinputstream FS = new fileinputstream (File );

Int data;

While (Data = FS. Read ())! =-1)

{

// Write the beginning of the MPs queue

POs. Write (data );

}

POs. Close ();

}

Catch (ioexception E)

{

System. Out. println ("sender error" + E );

}

}

}

// Thread read

Class extends er extends thread

{

Pipedinputstream Pis;

File file;

// Constructor

Extends Er (pipedinputstream PIs, string filename)

{

This. PIs = Pis;

File = new file (filename );

}

// Thread running

Public void run ()

{

Try

{

// Write a file stream object

Fileoutputstream FS = new fileoutputstream (File );

Int data;

// Read from the end of the MPs queue

While (Data = PIs. Read ())! =-1)

{

// Write a local file

FS. Write (data );

}

Pis. Close ();

}

Catch (ioexception E)

{

System. Out. println ("er error" + E );

}

}

}

VII. Random file read/write: randomaccessfile class

It directly inherits from the object class rather than the inputstream/outputstream class, so that data in any position in the file can be read and written (only the pointer of the file's read and write location needs to be changed ).

Programming steps:

① Generate a stream object and specify the read/write type;

② Mobile read/write location;

③ Read and Write File Content;

④ Close the file.

In addition, because the randomaccessfile class implements the interfaces of dataoutput and datainput, it can be used to read and write different types of basic data in Java (for example, the readlong () method is used to read long integers, And the readint () ).

Program instance:

In the hosts file.

Import java. Io .*;

Public class randomfilerw

{

Public static void main (string ARGs [])

{

Stringbuffer Buf = new stringbuffer ();

Char ch;

Try

{

While (CH = (char) system. In. Read ())! = '\ N ')

{

Buf. append (CH );

}

// The read/write mode can be "R" or "RW"

Randomaccessfile myfilestream = new randomaccessfile ("C: \ userinput.txt", "RW ");

Myfilestream. Seek (myfilestream. Length ());

Myfilestream. writebytes (BUF. tostring ());

// Add the content entered by the user from the keyboard to the end of the file

Myfilestream. Close ();

}

Catch (ioexception E)

{

}

}

}

8. datainput/dataoutput interfaces:

Read/write (such as readchar (), readint (), readlong (), and readfloat (), and Readline () returns a string ). The randomaccessfile class implements this interface and has a more flexible data read/write method than the fileinputstream or fileoutputstream class.

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.