chaojidawang 2023-05-11 20:25 采纳率: 25%
浏览 18
已结题

在使用java里的ByteBuffer向FileChannel写入的时候无法写入的问题

在使用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次的。请问各位,这代码有什么问题吗

  • 写回答

1条回答 默认 最新

  • Soulic 2023-05-11 22:27
    关注

    ByteBuffer.put之后调下ByteBuffer.flip试下

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月20日
  • 已采纳回答 5月12日
  • 创建了问题 5月11日

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应