Java-BufferOverflowException尝试写入文件2次或以上时

Java-BufferOverflowException尝试写入文件2次或以上时,java,file,exception,byte,bytebuffer,Java,File,Exception,Byte,Bytebuffer,我正在尝试编写一个程序,一次可以占用1位,然后在收集16位后将2个字节写入一个文件 以下是基本代码: public void addBit(int bit) throws IOException{ if(this.byteholder.length() < 16){ this.byteholder += "" + bit; } else{ write(); } } public void write() throws IOE

我正在尝试编写一个程序,一次可以占用1位,然后在收集16位后将2个字节写入一个文件

以下是基本代码:

public void addBit(int bit) throws IOException{
    if(this.byteholder.length() < 16){
        this.byteholder += "" + bit;
    }
    else{
        write();
    }
}

public void write() throws IOException{
    if(this.byteholder.length() == 16){
        System.out.println(this.byteholder);
        int a = Integer.parseInt(byteholder, 2);
        System.out.println(Integer.toBinaryString(a));
        ByteBuffer bytes = ByteBuffer.allocate(2).putInt(a);
        byte[] byteArray = bytes.array();

        out.write(byteArray);
        out.flush();
        this.byteholder = "";
    }


}

public static void main(String[] args) {
    try {
        File f = new File("test");
        BitFileWriter out = new BitFileWriter(f);
        for(int i=0; i<2; i++){
            out.addBit(1);
            out.addBit(0);
            out.addBit(0);
            out.addBit(1);
            out.addBit(0);
            out.addBit(1);
            out.addBit(1);
            out.addBit(0);
            out.addBit(1);
            out.addBit(0);
            out.addBit(0);
            out.addBit(1);
            out.addBit(0);
            out.addBit(1);
            out.addBit(1);
            out.addBit(0);
        }

        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

}
ByteBuffer.allocate2.putInta

您正在为一个整数分配2个字节,即4个字节。你预计会发生什么?如果要使用16位值,请使用short和putShort

如果由于签名问题而在使用short时遇到问题,1001011010010110被认为超过了short的值,则可以将a保留为int,但使用PUTSHORTA写入该值


至于您的文件保持为空,您可能没有在close方法中正确关闭资源,或者您忘记将缓冲区写入文件。

至于您的输出文件保持为空的原因:

您第一次调用write方法是在您尝试添加第17位并将其松开时


如果只进行一次迭代,即只尝试写入16位,则永远不会调用写入方法。因此,BufferOverflowException不会显示,但也不会写入文件。

您有堆栈跟踪吗?@SteveSmith Oops,谢谢提醒我。我现在发布了堆栈跟踪。在我尝试使用Int之前,我确实尝试使用Short。然而,当我使用a Short时,我得到一个NumberFormatException:值超出范围。值:1001010010110基数:2错误。知道为什么吗?看我的编辑。您可以继续使用int,但将其作为一个短字符写入缓冲区。谢谢您修复了它!只是一个小问题。。。一般来说,我对Java和编程相当陌生。到底应该把什么写入我的文件?我的档案应该显示什么?现在它只显示了两行,如:-不带引号ofc。文件大小现在显示2个字节,所以我想我做对了…它显示了写入文件的位,解释为单字节字符。如果您打印出Integer.ToBinarysting“-”,您应该会看到您编写的原始位模式。啊,感谢您现在修复了该部分。但仍会继续获取BufferOverflowException…Nvm它现在已修复!:
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Unknown Source)
at java.nio.HeapByteBuffer.putInt(Unknown Source)
at CompPck.BitFileWriter.write(BitFileWriter.java:30)
at CompPck.BitFileWriter.addBit(BitFileWriter.java:21)
at CompPck.BitFileWriter.main(BitFileWriter.java:66)