失效链接处理 |
JDK 1.4 Tutorial PDF 下载
本站整理下载:
相关截图:
![]()
主要内容:
1.1.4 Writing to a channel
Now that we’ve read some data from a channel into a buffer, we can write that data
out to another channel. This is done—surprise!—via the write() method of a chan-
nel. And, as with reading, writing a buffer is similar to doing a bulk-write from the
old java.io classes. Here is the old write() method:
public void write( byte[] b, int off, int len );
Again, the three arguments to the old-style write are replaced by a single argument,
which is a buffer, in the new write() method:
public int write( ByteBuffer src );
In this new method, you’ll see an important difference that you don’t see with the
read() methods: the new write() method returns an int . The old write() call was
guaranteed to write all the data or throw an exception. There were no valid condi-
tions under which it would write only part of the data and return. This is not the
case with the new write() method. It returns the number of bytes that were written.
And as with reading, if you write to a channel that is only open for reading, a
NonWritableChannelException will be thrown.
6 CHAPTER 1
Basic NIO
1.1.5 Reading and writing together
The CopyFile program (see listing 1.1) illustrates the entire process of copying all
the data from an input channel to an output channel.
Watch out for a couple of new methods— flip() and clear() . These methods
are used any time a buffer is both written to and read from—which is almost all of
the time. After reading from a channel into a buffer, you call buffer.flip() to pre-
pare the buffer for being written to another channel. Likewise, once you’ve finished
writing the contents of a buffer to one channel, you call buffer.clear() to prepare
it for being read into again. More about this in section 1.2.4.
Make sure not to confuse reading from a buffer with reading from a channel:
reading from a channel means reading data from the channel, and putting it into the
buffer. Likewise, writing data to a channel means getting data from a buffer, and
writing it to a channel. See section 1.2.2 for more details.
(see \Chapter1\CopyFile.java)
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CopyFile
{
static public void main( String args[] ) throws Exception {
String infile = args[0], outfile = args[1];
FileInputStream fin = new FileInputStream( infile );
FileOutputStream fout = new FileOutputStream( outfile );
FileChannel inc = fin.getChannel();
FileChannel outc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
while (true) {
int ret = inc.read( buffer );
if (ret==-1) // nothing left to read
break;
buffer.flip();
outc.write( buffer );
buffer.clear(); // Make room for the next read
}
}
}
|