在使用java里的ByteBuffer向FileChannel写入的时候无法写入的问题
代码如下
public static void main(String[] args) throws IOException {
testChannelWrite( "channelWrite" + UUID.randomUUID().toString() + ".txt");
}
public static void testChannelWrite(String filePath) throws IOException {
RandomAccessFile fis = new RandomAccessFile(filePath, "rw");
FileChannel channel = fis.getChannel();
StringBuilder sb = new StringBuilder();
ByteBuffer buffer = ByteBuffer.allocate(10_0000);
for (int i = 1; i < 1_000_000; i++) {
sb.append("你好");
}
if (sb.length() > 0)
writeToChannel(buffer, channel, sb.toString());
channel.close();
fis.close();
}
private static void writeToChannel(ByteBuffer buffer, FileChannel channel, String s) throws IOException {
buffer.clear();
byte[] bytes = s.getBytes();
int position = 0;
// 循环把bytes数据写入channel
while (position < bytes.length) {
int writeSize = Math.min(buffer.remaining(), bytes.length - position);
buffer.put(bytes, position, writeSize);
// 记录当前在byte的位置
position += writeSize;
if (buffer.remaining() == 0) {
channel.write(buffer);
buffer.clear();
}
}
if (buffer.remaining() != buffer.capacity()) {
channel.write(buffer);
channel.force(false);
buffer.clear();
}
}
结果只能在文件中写入一次‘你好’,而我是循环了1000000次的。请问各位,这代码有什么问题吗