Posts

Showing posts with the label Inputstream

Convert InputStream To Byte Array In Java

Answer : You can use Apache Commons IO to handle this and similar tasks. The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils.toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() . It handles large files by copying the bytes in blocks of 4KiB. You need to read each byte from your InputStream and write it to a ByteArrayOutputStream . You can then retrieve the underlying byte array by calling toByteArray() : InputStream is = ... ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } return buffer.toByteArray(); Finally, after twenty years, there’s a simple solution without the need for a 3rd party library, thanks to Java 9: InputStream is; … byte[] array = is.readAllBytes(); Note also the convenience met...

Converting EBCDIC To ASCII In Java

Answer : If I am interpreting this format correctly you have a binary file format with fixed-length records. Some of these records are not character data (COBOL computational fields?) So, you will have to read the records using a more low-level approach processing individual fields of each record: import java.io.*; public class Record { private byte[] kdgex = new byte[2]; // COMP private byte[] b1code = new byte[2]; // COMP private byte[] b1number = new byte[8]; // DISPLAY // other fields public void read(DataInput data) throws IOException { data.readFully(kdgex); data.readFully(b1code); data.readFully(b1number); // other fields } public void write(DataOutput out) throws IOException { out.write(kdgex); out.write(b1code); out.write(b1number); // other fields } } Here I've used byte arrays for the first three fields of the record but you could use other more suitable types where appropriate (like a short for the first field with rea...