lip();
fc.write(buffer);
实战练习
我们以一个名为 CopyFile.java 的简单程序作为这个练习的基础,它将一个文件的所有内容拷贝到另一个文件中。CopyFile.java 执行三个基本操作:首先创建一个Buffer,然后从源文件中将数据读到这个缓冲区中,然后将缓冲区写入目标文件。这个程序不断重复 ― 读、写、读、写 ― 直到源文件结束。
// CopyFile
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class CopyFile {
? ?
? ? static public void main( String args[] ) throws Exception {
? ? ? ? String infile="E:\\北京欢迎你.txt";
? ? ? ? String outfile="E:\\out.txt";
? ? ? ? FileInputStream fin=new FileInputStream(infile);
? ? ? ? FileOutputStream fout=new FileOutputStream(outfile);
? ? ? ? FileChannel fcin = fin.getChannel();
? ? ? ? FileChannel fcout = fout.getChannel();
? ? ? ? ByteBuffer buffer = ByteBuffer.allocate(1024);
? ? ? ? while (true) {
? ? ? ? ? ? buffer.clear();
? ? ? ? ? ? int r=fcin.read(buffer);
? ? ? ? ? ? if (r == -1) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? buffer.flip();
? ? ? ? ? ? fcout.write(buffer);
? ? ? ? }
? ? }
}

