下面的是nio channel的demo
import java.nio.channels.FileChannel; public class NioFileChannelTest { public static void main(String[] args) throws Exception{ // 创建一个字符串 String str = new String("你好,nio"); // 创建一个文件输出流 File file = new File("F://test.txt"); FileOutputStream fileOutputStream = new FileOutputStream(file); // 通过文件输出流,创建一个filechannel FileChannel channel = fileOutputStream.getChannel(); // 创建一个bytebuffer ByteBuffer buffer = ByteBuffer.allocate(1024); // 将str put到buffer中 buffer.put(str.getBytes()); // 将buffer 翻转 buffer.flip(); // 将buffer写入到channel中,write和read 是针对channel来说的 channel.write(buffer); fileOutputStream.close(); } }
注意点:一个utf-8的汉子 占用3个字节
读取channel数据的demo
public class NioFileChannelTest2 { public static void main(String[] args) throws Exception{ File file = new File("F://test.txt"); FileInputStream fileInputStream = new FileInputStream(file); ByteBuffer byteBuffer = ByteBuffer.allocate((int)file.length()); FileChannel channel = fileInputStream.getChannel(); channel.read(byteBuffer); byteBuffer.flip(); byte[] array = byteBuffer.array(); System.out.println(new String(array)); } }
好了