首页 > 代码库 > AsynchronousFileChannel的例子
AsynchronousFileChannel的例子
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
public class async_file {
static final int TRANS_RRQ = 1;
static final int TRANS_NAM = 2;
static final int TRANS_DATA = http://www.mamicode.com/3;
static final int TRANS_ACK = 4;
static final int TRANS_ERROR = 5;
static final int TRANS_END = 6;
AsynchronousFileChannel afc = null;
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
{
System.out.println(byteBuffer.order() + " " + ByteOrder.nativeOrder());
byteBuffer.order(ByteOrder.nativeOrder());
}
public async_file() {
try {
afc = AsynchronousFileChannel.open(Paths.get("ftext.bin"),
StandardOpenOption.CREATE, StandardOpenOption.WRITE);
afc.truncate(0); //如果存在则截断为零
byteBuffer.clear();
System.out.println(byteBuffer.order());
byteBuffer.putShort((short) TRANS_RRQ);
byteBuffer.putShort((short) 0);
byteBuffer.put("recent".getBytes());
byteBuffer.flip();
byteBuffer.limit(0x20);
System.out.println(byteBuffer.remaining()+" "+byteBuffer.limit());
Future<Integer> fw = afc.write(byteBuffer,afc.size());
while(!fw.isDone());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new async_file();
}
}
新建文件用异步通道写32个字节的LITTLE_ENDIAN数据到文件中
AsynchronousFileChannel的例子