Using BufferedOutputStream to write bytes to file with while loop. Help needed

徘徊边缘 提交于 2019-12-13 03:59:18

问题


I'm trying to write bytes to a file with a BufferedOutputStream but I need this to work in a while loop. This is mean to work with a TFTP server. It writes the file with absolutely nothing in it (which is pointless). Can anyone help me with this?

            WRQ WRQ = new WRQ();
            ACK ACK = new ACK();
            DatagramPacket outPacket;
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
            byte[] bytes;
            byte[] fileOut;
            outPacket = WRQ.firstPacket(packet);
            socket.send(outPacket);

            socket.receive(packet);

            while (packet.getLength() == 516){

            bytes = WRQ.doWRQ(packet);
            bufferedOutput.write(bytes);

            outPacket = ACK.doACK(packet);
            socket.send(outPacket);

            socket.receive(packet); 

            }

            bytes = WRQ.doWRQ(packet);
            bufferedOutput.write(bytes);

            outPacket = ACK.doACK(packet);
            socket.send(outPacket);

回答1:


You're not closing the stream when you're done with it.




回答2:


Are you missing bufferedOutput.flush() to flush out all the buffered data.




回答3:


Just try and close your BufferedOutputStream.

Add bufferedOutput.close();

If you don't close your OutputStream, you could lose buffered data, that is what is happening in your case maybe. Either close it, or flush it.




回答4:


You will need to use the BufferedOutputStream's flush() method so that all results would be written out. Invoking the close() method also performs a flush().

http://www.javapractices.com/topic/TopicAction.do?Id=8



来源:https://stackoverflow.com/questions/10674665/using-bufferedoutputstream-to-write-bytes-to-file-with-while-loop-help-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!