此代码在文件通道中写入两个字符串
final byte[] title = "Title: ".getBytes("UTF-16");
final byte[] body = "This is a string.".getBytes("UTF-16");
ByteBuffer titlebuf = ByteBuffer.wrap(title);
ByteBuffer bodybuf = ByteBuffer.wrap(body);
FileChannel fc = FileChannel.open(p, READ, WRITE, TRUNCATE_EXISTING);
fc.position(title.length); // second string written first, but not relevant to the problem
while (bodybuf.hasRemaining()) fc.write(bodybuf);
fc.position(0);
while (titlebuf.hasRemaining()) fc.write(titlebuf);
每个字符串都以 BOM 为前缀。
[Title: ?T] *254 255* 0 84 0 105 0 116 0 108 0 101 58 0 32 *254 255* 0 84
虽然在文件的开头有一个是可以的,但是当流的中间有一个时会产生问题。
我怎样才能防止这种情况发生?