本文主要是介绍利用FileChannel完成文件的读、写、复制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
内容:通过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();}
}
这篇关于利用FileChannel完成文件的读、写、复制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!