package com.netty.bufferandchannel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Fighting
* @version BufferAndChannel, v 0.1 2020/8/11 23:27 Fighting
* @Content 使用nio实现向文件中写入字符串
*
* --------------------------------------------
* --------------JDK io FileOutPutStream
* ---------------^^^
* ---------------||FileChannel [FileChannelImpl]
* ---------------^^^^^^
* ----------------Buffer [Bytebuffer]
* ----------------^^^数据^^^
*/
public class BufferAndChannelWrite {
public static void main(String[] args) throws IOException {
String str = "hello,Fighting中文";//一个中文用UTF-8编码转为字节时占用3个字节
FileOutputStream fileOutputStream = new FileOutputStream("G:\\netty-workspace\\netty-test\\src\\main\\java\\com\\netty\\bufferandchannel\\demo.txt");
//通过原生io Api获取nio中的channel
FileChannel channel = fileOutputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
//将字符串放入buffer
buffer.put(str.getBytes());
//由写入改为读取
//position limit
//position limit 的变化
buffer.flip();
//buffer中的数据写入到channel
// public int write(ByteBuffer var1)//将缓冲区的数据写入到通道中
channel.write(buffer);
fileOutputStream.close();
}
}
public abstract class Buffer {
private int mark = -1;
private int position = 0;
private int limit;
private int capacity;
}
在调用的时候需要特别看一下Buffer类中这几个参数的变化!
理解:
channel.write(buffer);//此处还需要补充,限于水平没能理解此处将缓冲区的数据写入通道后调用底层的IOUtils.write(Buffer bf),便完成了输出数据...
FileOutputStream
public class FileOutputStream extends OutputStream
{
/**
* The system dependent file descriptor.
*/
private final FileDescriptor fd;
/**
* True if the file is opened for append.
*/
private final boolean append;
/**
* The associated channel, initialized lazily.
*/
private FileChannel channel;
}
可见原始io.FileOutputStream中包含了channel的对应操作。