内容:通过NIO中的FileChannel完成文件的读、写、复制。
public class NioFileCopy { private RandomAccessFile aFile = null; private FileChannel inChannel = null; private final ByteBuffer buf = ByteBuffer.allocate(1024); public void doWrite() throws IOException { aFile = new RandomAccessFile("C:/goods.txt", "rw"); inChannel = aFile.getChannel(); String newData = "New String to wirte to file... " + System.currentTimeMillis(); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while (buf.hasRemaining()) inChannel.write(buf); inChannel.close(); System.out.println("Write Over"); } public void doRead() throws IOException { aFile = new RandomAccessFile("C:/goods.txt", "rw"); inChannel = aFile.getChannel(); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while (buf.hasRemaining()) System.out.print((char) buf.get()); buf.clear(); bytesRead = inChannel.read(buf); } aFile.close(); } public void doCopy() throws IOException { aFile = new RandomAccessFile("C:/goods.txt", "rw"); inChannel = aFile.getChannel(); RandomAccessFile bFile = new RandomAccessFile("C:/22.log", "rw"); FileChannel outChannel = bFile.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); System.out.println("Copy over"); } public static void main(String[] args) throws IOException { NioFileCopy tool = new NioFileCopy(); //tool.doWrite(); //tool.doRead(); tool.doCopy(); } }
时间: 2024-10-14 01:16:39