Yesterday saw the internal implementation of the FileInputStream class, in addition to inheriting from the InputStream class, but also added a FileChannel method, through the Getchannel () method to obtain the channel of the file, Today, look at what the FileChannel is doing, what is more powerful than FileInputStream, and what is the internal implementation of it?
Here's a look at what the FileChannel concrete class implementation looks like:
You can begin to see an introduction to related classes:
A channel for reading, writing, mapping, and manipulating a file.
A channel for reading, mapping, and manipulating files.
The class definition is as follows:
Publicabstractclass FileChannel
Extends Abstractinterruptiblechannel
Implements Seekablebytechannel, Gatheringbytechannel, Scatteringbytechannel
Implemented a lot of interfaces ah ... However, these interfaces will certainly encounter and understand their main functions in the future. This article mainly studies the FileChannel class
Protected FileChannel () {}
A protected construction method that can only be accessed by itself and its subclasses. The following method is provided by jdk1.7:
Publicstatic FileChannel Open (path path,
Set<?extends Openoption>options,
FILEATTRIBUTE<?>...ATTRS)
Throws IOException
{
Filesystemproviderprovider = Path.getfilesystem (). Provider ();
Return Provider.newfilechannel (PATH,OPTIONS,ATTRS);
}
The path path class is used to get filesystemprovider and create a FileChannel object to manipulate the file
Privatestatic final fileattribute<?>[] no_attributes =new fileattribute[0];
Provide default file properties
Publicstatic FileChannel Open (path path, openoption...options)
Throws IOException
{
Set<openoption>set = new hashset<openoption> (options.length);
Collections.addall (set,options);
Return open (path,set,no_attributes);
}
Also a class function that returns the FileChannel object
/**
* Reads a sequence of bytes from-channel into the given buffer.
*
*<p> Bytes are read starting at this channel ' s current file position, and
* Then the file position is updated with the number of bytes actually
* Read. Otherwise this method behaves the exactly as specified in the{@link
* Readablebytechannel} interface.</p>
*/
public abstract int Read (Bytebuffer DST) throws IOException;
The above function, which is different from the read in FileInputStream, reads channel from the current position to the buffered object and increases the value of the current position in the Channel channel.
Publicabstract Long Read (bytebuffer[] dsts,int offset, intlength)
Throws IOException;
Reads data from the current location to multiple buffered objects. Offset and length are not indicated, and return can be judged by the implementation of other subclasses.
publicabstract int Write (Bytebuffer src) throws IOException;
Reads the data from the buffered object to the current position of the channel, and if channel is an append mode, it is appended to the end and the file increases.
Publicabstract long Position () throws IOException;
Gets the location of the file for the current channel, and throws an exception if channel is closed.
Publicabstract filechannel Position (longnewposition) throws IOException;
Reset the location of the file. However, the file size is not changed.
If you set the location after the file terminator and then try to read the data from the file channel, the Read method returns the -1--file end flag.
If you set the location after the end of the file and then write the data to the channel, the file will hold up to the current location and write the data. This can result in a "file hole" where there is a gap between the data written in the physical file on the disk.
Publicabstractlong size () throws IOException;
Return file size
Publicabstract FileChannel truncate (longsize) throws IOException;
Shorten the channel file to a specified size, if larger than the source file size, the file size is unchanged, if smaller than the original file size, then shorten the file to a specified size. You can use the Filechannel.truncate () method to intercept a file. When you intercept a file, the portion of the file that follows the specified length will be deleted.
Publicabstractlong TransferTo (Longposition,longcount,
Writablebytechanneltarget)
Throws IOException;
Transfers the specified length from the specified position in the channel stream to another writable channel.
Publicabstract Long Transferfrom (READABLEBYTECHANNELSRC,
Long position, LongCount)
Throws IOException;
Transfer the data from this channel channel to a different readable channel.
publicabstract int Read (Bytebuffer dst,long position) throws IOException;
Reads the bytes starting at the specified position into the byte buffer object
publicabstract int Write (bytebuffer src,long position) throws IOException;
Writes to the Bytebuffer object, starting at the specified location.
The Filechannel.force () method forces data that has not been written to disk in the channel to be written to disk. For performance reasons, the operating system caches data in memory, so it is not guaranteed that the data written to the FileChannel will be written to disk immediately. To ensure this, you need to invoke the force () method.
The Force () method has a Boolean parameter that indicates whether file metadata (permission information, and so on) is also written to disk.
The following example forces file data and metadata to be written to disk at the same time:
There are some other ways behind this class. It's too abstract to write back. To understand the essence of FileChannel, but also through the code example to verify the function of the method to remember a bit more profound, here to sum up the class used in some of the other classes, but also you do not see the class:
Abstractinterruptiblechannel, Seekablebytechannel, Gatheringbytechannel, Scatteringbytechannel,
Path, Openoption, FileAttribute, Bytebuffer, Writablebytechannel, Readablebytechannel.
To understand the use of filechannel thoroughly, you need to understand the Bytebuffer object model to get it done.
<span style= "White-space:pre" > </span><span style= "font-family:comic Sans;"
>file file = new file ("/users/terrylmay/desktop/in.txt");
File outfile = new file ("/users/terrylmay/desktop/out.txt");
FileInputStream fis = new FileInputStream (file);
FileOutputStream fos = new FileOutputStream (outfile);
Get channel FileChannel Channelin = Fis.getchannel () via file flow;
FileChannel channelout = Fos.getchannel ();
Allocating 50 bytes of space to the buffer bytebuffer buffer = bytebuffer.allocate (50);
while (channelin.read (buffer)!=-1) {//Get the position in channel, this position should be 0 System.out.println ("The current position of the channel:" +channelin.position ());
public abstract int Read (Bytebuffer DST) throws IOException;
Reads a series of bytes from the channel position to the buffered object.
Channelin.read (buffer);
This side prints the current position of the channel channel (the print value is System.out.println) (the current position of the channel: +channelin.position ()); You can also look at what the Channel.size () return value is at this time.
(File size)
System.out.println ("The size return value of the channel:" +channelin.size ()); SYSTEM.OUT.PRINTLN ("Data in Buffer:" +buffer.tostring ());
Change the mode of the buffer-read mode. Then position into Limit,channel from the buffer of 0 read to limit.
Buffer.flip ();
SYSTEM.OUT.PRINTLN ("Data in Buffer:" +buffer.tostring ());
This clears the data channelout.write (buffer) in the buffer;
Positon 0 means that there is no data in the Bytebuffer System.out.println ("Data in Buffer:" +buffer.tostring ());
Buffer.clear (); }</span>This example uses a file input output stream to obtain the channel, reads data from the channel to the buffer, and reads the data from the buffer to the output channel. The Buffer.flip () method must be invoked to convert to read mode, otherwise the data may be read in error. The specific reason is because, for example, there are 30 bytes in a file, set the buffer space of 50byte, then in the input stream from the buffer in the time, will set the buffer in the position=30,limit=capacity= 50, the data only exists with the 0-30 part of the buffer. If the flip () method is not invoked, then limit = 30,position = 0 is not made, causing the data to be read or read from the position. To the end of the limit. You can't read the correct data. The output file will not replicate anything in the past. Remember to close the file stream once you have finished using it.