DMo
DMo

Reputation: 621

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

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);

Upvotes: 0

Views: 1477

Answers (4)

user1348384
user1348384

Reputation: 83

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

Upvotes: 0

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

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.

Upvotes: 0

Danish Shrestha
Danish Shrestha

Reputation: 487

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

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198211

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

Upvotes: 3

Related Questions