简体   繁体   中英

Outputting byte[] to a .txt file

I'm trying to output a byte array to a file. The String that I create displays correctly when I call System.out.println(ouput_stream). Hover, it does not output correctly when I use a FileOutputStream. Here's what I've got so far. Any suggestions?

FileOutputStream fos = new FileOutputStream("outputFile.txt"); 
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

String received_string = new String(rPacket.getData(), 0, rPacket.getLength(), "UTF-8");

System.out.println(received_string);
out.write(received_string, 0, received_string.length());

The console displays the information the information when I call the System.out.println(received_string. However, it doesn't output the file correctly. I asked a similar question earlier, but now am struggling on the output. Thanks for any help.

Have a look at Apache Commons FileUtils.writeByteArrayToFile

Should do what you need

Your code looks a bit weird (do you want bytes or Strings), but should be okay.

What did you find in the file? Did you close the stream/writer before looking at it? If not, it is likely still being buffered somewhere.

Try to avoid the conversion to String, though, if you really want to just pipe that packet to a file.

Don't use a String or a Writer at all. Just copy the bytes directly from the packet to the file:

fos.write(rPacket.getData(), rPacket.getOffset(), rPacket.getLength());

Then you can't possibly corrupt the data.

Try using BufferedWriter ..

BufferedWriter writer = new BufferedWriter(new FileWriter("outfile"));
writer.write(received_string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM