package stream.demo1;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TransferTo
{
/**
* 相对于ChannelCopy,该方法具有更好的效率
*/
public static void main(String[] args)
throws IOException
{
if (args.length != 2)
{
System.out.println("arguments : sourcefile destfile");
System.exit(1);
}
FileChannel in = new FileInputStream(args[0]).getChannel();
FileChannel out = new FileOutputStream(args[1]).getChannel();
// 把输入流和输出流相连,在数据的读取和写入时可以考虑这个
in.transferTo(0, in.size(), out);// or out.transferFrom(in, 0, in.size());
}
}
package stream.demo1;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelCopy
{
private static final int BSIZE = 1024;
public static void main(String[] args)
throws Exception
{
if (args.length != 2)
{
System.out.println("arguments : siyrcefuke destfuke");
System.exit(1);
}
FileChannel in = new FileInputStream(args[0]).getChannel();
FileChannel out = new FileOutputStream(args[1]).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while (in.read(buffer) != -1)
{
buffer.flip();
out.write(buffer);
buffer.clear();
}
}
}
package stream.demo1;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class GetChannel
{
private static final int BSIZE = 1024;
public static void main(String[] args)
throws Exception
{
// FileChannel用于读取、写入、映射和操作文件的通道。
FileChannel fc = new FileOutputStream("data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some more".getBytes()));// ByteBuffer.wrap("Some more".getBytes()) 将字节数组包装到缓冲区中。
fc.close();
// RandomAccessFile文件操作类,RandomAccessFile是一个很特殊的IO操作类,对文件可以既可以读,也可以写,甚至可以跳过一些数据进行操作
fc = new RandomAccessFile("data.txt", "rw").getChannel();
fc.position(fc.size());// 把指针移动fc.size的距离进行数据操作
fc.write(ByteBuffer.wrap("Some more".getBytes()));
fc.close();
fc = new FileInputStream("data.txt").getChannel();
// ByteBuffer.allocate(BSIZE) 分配一个新的字节缓冲区
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
fc.read(buffer);
buffer.flip();
while (buffer.hasRemaining())
System.out.print((char)buffer.get());
}
}