我现在正在学习java NIO,我找到了一个例子来解释FileChannel的收集操作,如下所示:
public class ScattingAndGather {
public static void main(String args[]) {
gather();
}
public static void gather() {
ByteBuffer header = ByteBuffer.allocate(10);
ByteBuffer body = ByteBuffer.allocate(10);
byte[] b1 = { '0', '1' };
byte[] b2 = { '2', '3' };
header.put(b1);
body.put(b2);
ByteBuffer[] buffs = { header, body };
FileOutputStream os = null;
FileChannel channel = null;
try {
os = new FileOutputStream("d:/scattingAndGather.txt");
channel = os.getChannel();
channel.write(buffs);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
虽然结果显示文件已经创建,但它是空的,应该是0123,这个例子有什么问题?
至尊宝的传说
相关分类