FileChannel主要用來進行對本地文件進行IO操做
1.public int read(ByteBuffer dst):從通道讀取數據並放到緩存區中
2.public int write(ByteBuffer src):把緩衝區的數據寫到通道中
3.public long transferFrom(ReadableByteChannel src,long position,long count):從目標通道中複製數據到當前通道
4.public long transferTo(long position,long count,WritableByteChannel target):把數據從當前通道複製給目標通道java
本地文件寫數據緩存
import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileChannel01 { public static void main(String[] args) throws Exception { String s = "test"; FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/test.txt"); FileChannel fileChannel = fileOutputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.put(s.getBytes()); byteBuffer.flip(); fileChannel.write(byteBuffer); fileOutputStream.close(); } }
本地文件讀數據code
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileChannel02 { public static void main(String[] args) throws Exception { File file = new File("/Users/liaowh/Desktop/test.txt"); FileInputStream fileInputStream = new FileInputStream(file); FileChannel fileChannel = fileInputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length()); fileChannel.read(byteBuffer); System.out.println(new String(byteBuffer.array())); fileInputStream.close(); } }
使用一個Buffer完成文件拷貝ip
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileChannel03 { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("/Users/liaowh/Desktop/test.txt"); FileChannel fileChannel01 = fileInputStream.getChannel(); FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/test2.txt"); FileChannel fileChannel02 = fileOutputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); while(true){ byteBuffer.clear(); int read = fileChannel01.read(byteBuffer); if(read == -1){ break; } byteBuffer.flip(); fileChannel02.write(byteBuffer); } fileInputStream.close(); fileOutputStream.close(); } }
使用transferFrom()完成文件拷貝get
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class NIOFileChannel04 { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("/Users/liaowh/Desktop/test.txt"); FileOutputStream fileOutputStream = new FileOutputStream("/Users/liaowh/Desktop/dest.txt"); FileChannel source = fileInputStream.getChannel(); FileChannel dest = fileOutputStream.getChannel(); dest.transferFrom(source,0,source.size()); source.close(); dest.close(); fileInputStream.close(); fileOutputStream.close(); } }