Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I have to read a binary file in a legacy format with Java. In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars. In any other language I would create structs (C/C++) or records (Pascal/Delphi) which are byte-by-byte representations of the header and the record. Then I'd ...
I need to parse some simple binary Files. (The files contains n entries which consists of several signed/unsigned Integers of different sizes etc.) In the moment i do the parsing "by hand". Does somebody know a library which helps to do this type of parsing? Edit: "By hand" means that i get the Data Byte by Byte sort it in to the correct Order and convert it to an Int/Byte etc. Also some of t...
I'm reading a binary file like this: InputStream in = new FileInputStream( file ); byte[] buffer = new byte[1024]; while( ( in.read(buffer ) > -1 ) { int a = // ??? } What I want to do it to read up to 4 bytes and create a int value from those but, I don't know how to do it. I kind of feel like I have to grab 4 bytes at a time, and perform one "byte" operation ( like >> << >>...
The JavaDoc says "The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls." But what does this even mean? What's an embedded null in this context? I am trying to convert from a Java saved UTF-8 string to "real" UTF-8.
I have a program that I made in Python to find specific tags in TIFF IFD's and return the values. It was just a proof of concept thing in python, and now I need to move the functionality to java. I think I can just use the String(byteArray[]) constructor for the ASCII data types, but I still need to get Unsigned short (2 byte) and unsigned long (4 byte) values. I don't need to write them back t...
I was writing an article in which I wanted to show how to send objects across the network, from Java to CLR/.Net and Back. http://ferozedaud.blogspot.com/2009/11/howto-serialize-data-from-object-from.html While doing research for this, I could not find a Java equivalent for BitConverter class that exists in .NET. Due to this, I had to resort to using ByteBuffer to marshal primitive types to b...
I'm working on some Java <-> Perl interaction. I would like to know what the best way is to pass information from Perl to Java. (Great answers about Perl and Java here and here btw). There's a lot of text and XML(XML::Twig) I'm parsing in Perl, in a script I'm supposed to call from a Java Web App. So I have all this gathered data, and I need it to use it inside certain objects in Java. Wh...
Currently, I'm saving and loading some data in C/C++ structs to files by using fread()/fwrite(). This works just fine when working within this one C app (I can recompile whenever the structure changes to update the sizeof() arguments to fread()/fwrite()), but how can I load this file in other programs without knowing in advance the sizeof()s of the C struct? In particular, I have written this...
I have numbers written as ASCII codes in my file. For example "9" is stored as two bytes 57 i.e. 8 bits in total. I want to optimize storage by just storing those numbers as binary values for example numbers from 0-9 to be stored using 4 bits only. Any help?!
How do I convert a long to a byte[] and back in Java? I'm trying convert a long to a byte[] so that I will be able to send the byte[] over a tcp connection. On the other side I want to take that byte[] and convert it back into a double. Any tips would be appreciated.
I'm writing a simple client/server network application that sends and receives fixed size messages through a TCP socket. So far, I've been using the getInputStream() and getOutputStream() methods of the Socket class to get the streams and then call the read(byte[] b, int off, int len) method of the InputStream class to read 60 bytes each time (which is the size of a message). Later on, I read...
I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message. I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java sid...
I'm making a chat client that uses special encryption. It has a problem reading letters like «, ƒ, ̕ from the input buffer. Im reading them into a byte array and I tried using Connection.getInputStream().read(); And also using BufferedReader myInput = new BufferedReader( new InputStreamReader(Connection.getInputStream())); But there appears to be a problem as it displays them as squ...
I have a file of integers arranged like this: 1 2 3 55 22 11 (and so on) And I want to read in these numbers as fast as possible to lessen the total execution time of my program. So far, I am using a scanner with good results. However, I get the feeling that there exists a faster IO utility I can use. Can anyone please point me in the right direction? EDIT: So yes, I verified that it is th...
I have a binary file that I read byte by byte. I come across a section that is 8bytes long holding a double precision float (little endian). I can't figure out how to read this in and calculate it properly with masking and/or casting. (To be specific, the file type is .LAS, but that shouldn't matter). Anyone with any Java tricks? Thank you for your help.
I know the file structure, suppose this structure is this: [3-bytes long int],[1-byte long unsigned integer],[4-bytes long unsigned integer] So the file contains chains of such records. What is the most elegent way to parse such a file in Java? Supposedly, we can define a byte[] array of overall length and read it with InputStream, but how then convert its subelements into correct integer ...
How can I "modify" an InputStream? I have a file as input, I would like to modify some variable and forward a new InputStream. For example, the initial InputStream contains Hello ${var}. Then I want to "modify" this InputStream with var = "world", resulting an InputStream Hello world. What's the best practice to do this? Thanks.
What is the best possible way to send an int through a socket in Java? Right now I'm looking at sockout.write((byte)( length >> 24 )); sockout.write((byte)( (length << 8) >> 24 )); sockout.write((byte)( (length << 16) >> 24 )); sockout.write((byte)( (length << 24) >> 24 )); and then trying to rebuild the int from bytes on the other side, but it does...
How would you parse in Java a structure, similar to this \\Header (name)\\\ 1JohnRide 2MarySwanson 1 password1 2 password2 \\\1 block of data name\\\ 1.ABCD 2.FEGH 3.ZEY \\\2-nd block of data name\\\ 1. 123232aDDF dkfjd ksksd 2. dfdfsf dkfjd .... etc Suppose, it comes from a text buffer (plain file). Each line of text is "\n" - limited. Space is used between the words. The struc...
I have a couple of questions regarding the Bittorrent Peer Wire Protocol. I am trying to implement it in Java using this spec. In Peer Wire Protocol section it says that all integers are four byte big endian values. AFAIK java uses big endian. Does that mean say if i want to send a choke message choke:<len=0001><id=0> Do i just write to the sokcet 1 followed by 0? As for my seco...
I am trying to convert scientific double to decimal double in java. I am sending a value from server (coded on C++) which is running on X86 (little endian) machine and I was using htonl, ntohl methods for convertion before sending data to client (coded on java). But now, I have to sent this value with no conversion like LE to BE. The coversion is being done on client (java) side. Other type can...
  /*
   * Copyright 1994-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.io;

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.

Author(s):
Arthur van Hoff
Since:
JDK1.0
See also:
DataOutputStream
 
 public
 class DataInputStream extends FilterInputStream implements DataInput {

    
Creates a DataInputStream that uses the specified underlying InputStream.

Parameters:
in the specified input stream
 
     public DataInputStream(InputStream in) {
         super(in);
     }

    
working arrays initialized on demand by readUTF
 
     private byte bytearr[] = new byte[80];
     private char chararr[] = new char[80];

    
Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

The read(b) method has the same effect as:

 read(b, 0, b.length)
 

Parameters:
b the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Throws:
IOException if the first byte cannot be read for any reason other than end of file, the stream has been closed and the underlying input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
InputStream.read(byte[],int,int)
 
     public final int read(byte b[]) throws IOException {
        return .read(b, 0, b.length);
    }

    
Reads up to len bytes of data from the contained input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected.

Parameters:
b the buffer into which the data is read.
off the start offset in the destination array b
len the maximum number of bytes read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Throws:
java.lang.NullPointerException If b is null.
java.lang.IndexOutOfBoundsException If off is negative, len is negative, or len is greater than b.length - off
IOException if the first byte cannot be read for any reason other than end of file, the stream has been closed and the underlying input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
InputStream.read(byte[],int,int)
    public final int read(byte b[], int offint lenthrows IOException {
        return .read(bofflen);
    }

    
See the general contract of the readFully method of DataInput.

Bytes for this operation are read from the contained input stream.

Parameters:
b the buffer into which the data is read.
Throws:
EOFException if this input stream reaches the end before reading all the bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final void readFully(byte b[]) throws IOException {
        readFully(b, 0, b.length);
    }

    
See the general contract of the readFully method of DataInput.

Bytes for this operation are read from the contained input stream.

Parameters:
b the buffer into which the data is read.
off the start offset of the data.
len the number of bytes to read.
Throws:
EOFException if this input stream reaches the end before reading all the bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final void readFully(byte b[], int offint lenthrows IOException {
        if (len < 0)
            throw new IndexOutOfBoundsException();
        int n = 0;
        while (n < len) {
            int count = .read(boff + nlen - n);
            if (count < 0)
                throw new EOFException();
            n += count;
        }
    }

    
See the general contract of the skipBytes method of DataInput.

Bytes for this operation are read from the contained input stream.

Parameters:
n the number of bytes to be skipped.
Returns:
the actual number of bytes skipped.
Throws:
IOException if the contained input stream does not support seek, or the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
    public final int skipBytes(int nthrows IOException {
        int total = 0;
        int cur = 0;
        while ((total<n) && ((cur = (int.skip(n-total)) > 0)) {
            total += cur;
        }
        return total;
    }

    
See the general contract of the readBoolean method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the boolean value read.
Throws:
EOFException if this input stream has reached the end.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final boolean readBoolean() throws IOException {
        int ch = .read();
        if (ch < 0)
            throw new EOFException();
        return (ch != 0);
    }

    
See the general contract of the readByte method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next byte of this input stream as a signed 8-bit byte.
Throws:
EOFException if this input stream has reached the end.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final byte readByte() throws IOException {
        int ch = .read();
        if (ch < 0)
            throw new EOFException();
        return (byte)(ch);
    }

    
See the general contract of the readUnsignedByte method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next byte of this input stream, interpreted as an unsigned 8-bit number.
Throws:
EOFException if this input stream has reached the end.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final int readUnsignedByte() throws IOException {
        int ch = .read();
        if (ch < 0)
            throw new EOFException();
        return ch;
    }

    
See the general contract of the readShort method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next two bytes of this input stream, interpreted as a signed 16-bit number.
Throws:
EOFException if this input stream reaches the end before reading two bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final short readShort() throws IOException {
        int ch1 = .read();
        int ch2 = .read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (short)((ch1 << 8) + (ch2 << 0));
    }

    
See the general contract of the readUnsignedShort method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next two bytes of this input stream, interpreted as an unsigned 16-bit integer.
Throws:
EOFException if this input stream reaches the end before reading two bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final int readUnsignedShort() throws IOException {
        int ch1 = .read();
        int ch2 = .read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (ch1 << 8) + (ch2 << 0);
    }

    
See the general contract of the readChar method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next two bytes of this input stream, interpreted as a char.
Throws:
EOFException if this input stream reaches the end before reading two bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final char readChar() throws IOException {
        int ch1 = .read();
        int ch2 = .read();
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (char)((ch1 << 8) + (ch2 << 0));
    }

    
See the general contract of the readInt method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next four bytes of this input stream, interpreted as an int.
Throws:
EOFException if this input stream reaches the end before reading four bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final int readInt() throws IOException {
        int ch1 = .read();
        int ch2 = .read();
        int ch3 = .read();
        int ch4 = .read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }
    private byte readBuffer[] = new byte[8];

    
See the general contract of the readLong method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next eight bytes of this input stream, interpreted as a long.
Throws:
EOFException if this input stream reaches the end before reading eight bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
FilterInputStream.in
    public final long readLong() throws IOException {
        readFully(, 0, 8);
        return (((long)[0] << 56) +
                ((long)([1] & 255) << 48) +
                ((long)([2] & 255) << 40) +
                ((long)([3] & 255) << 32) +
                ((long)([4] & 255) << 24) +
                (([5] & 255) << 16) +
                (([6] & 255) <<  8) +
                (([7] & 255) <<  0));
    }

    
See the general contract of the readFloat method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next four bytes of this input stream, interpreted as a float.
Throws:
EOFException if this input stream reaches the end before reading four bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
readInt()
java.lang.Float.intBitsToFloat(int)
    public final float readFloat() throws IOException {
        return Float.intBitsToFloat(readInt());
    }

    
See the general contract of the readDouble method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
the next eight bytes of this input stream, interpreted as a double.
Throws:
EOFException if this input stream reaches the end before reading eight bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See also:
readLong()
java.lang.Double.longBitsToDouble(long)
    public final double readDouble() throws IOException {
        return Double.longBitsToDouble(readLong());
    }
    private char lineBuffer[];

    
See the general contract of the readLine method of DataInput.

Bytes for this operation are read from the contained input stream.

Deprecated:
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
     DataInputStream d = new DataInputStream(in);
 
with:
     BufferedReader d
          = new BufferedReader(new InputStreamReader(in));
 
Returns:
the next line of text from this input stream.
Throws:
IOException if an I/O error occurs.
See also:
BufferedReader.readLine()
FilterInputStream.in
    @Deprecated
    public final String readLine() throws IOException {
        char buf[] = ;
        if (buf == null) {
            buf =  = new char[128];
        }
        int room = buf.length;
        int offset = 0;
        int c;
loop:   while (true) {
            switch (c = .read()) {
              case -1:
              case '\n':
                break loop;
              case '\r':
                int c2 = .read();
                if ((c2 != '\n') && (c2 != -1)) {
                    if (!( instanceof PushbackInputStream)) {
                        this. = new PushbackInputStream();
                    }
                    ((PushbackInputStream)).unread(c2);
                }
                break loop;
              default:
                if (--room < 0) {
                    buf = new char[offset + 128];
                    room = buf.length - offset - 1;
                    System.arraycopy(, 0, buf, 0, offset);
                     = buf;
                }
                buf[offset++] = (charc;
                break;
            }
        }
        if ((c == -1) && (offset == 0)) {
            return null;
        }
        return String.copyValueOf(buf, 0, offset);
    }

    
See the general contract of the readUTF method of DataInput.

Bytes for this operation are read from the contained input stream.

Returns:
a Unicode string.
Throws:
EOFException if this input stream reaches the end before reading all the bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
UTFDataFormatException if the bytes do not represent a valid modified UTF-8 encoding of a string.
See also:
readUTF(java.io.DataInput)
    public final String readUTF() throws IOException {
        return readUTF(this);
    }

    
Reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String. The details of the modified UTF-8 representation are exactly the same as for the readUTF method of DataInput.

Parameters:
in a data input stream.
Returns:
a Unicode string.
Throws:
EOFException if the input stream reaches the end before all the bytes.
IOException the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
UTFDataFormatException if the bytes do not represent a valid modified UTF-8 encoding of a Unicode string.
See also:
readUnsignedShort()
    public final static String readUTF(DataInput inthrows IOException {
        int utflen = in.readUnsignedShort();
        byte[] bytearr = null;
        char[] chararr = null;
        if (in instanceof DataInputStream) {
            DataInputStream dis = (DataInputStream)in;
            if (dis.bytearr.length < utflen){
                dis.bytearr = new byte[utflen*2];
                dis.chararr = new char[utflen*2];
            }
            chararr = dis.chararr;
            bytearr = dis.bytearr;
        } else {
            bytearr = new byte[utflen];
            chararr = new char[utflen];
        }
        int cchar2char3;
        int count = 0;
        int chararr_count=0;
        in.readFully(bytearr, 0, utflen);
        while (count < utflen) {
            c = (intbytearr[count] & 0xff;
            if (c > 127) break;
            count++;
            chararr[chararr_count++]=(char)c;
        }
        while (count < utflen) {
            c = (intbytearr[count] & 0xff;
            switch (c >> 4) {
                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                    /* 0xxxxxxx*/
                    count++;
                    chararr[chararr_count++]=(char)c;
                    break;
                case 12: case 13:
                    /* 110x xxxx   10xx xxxx*/
                    count += 2;
                    if (count > utflen)
                        throw new UTFDataFormatException(
                            "malformed input: partial character at end");
                    char2 = (intbytearr[count-1];
                    if ((char2 & 0xC0) != 0x80)
                        throw new UTFDataFormatException(
                            "malformed input around byte " + count);
                    chararr[chararr_count++]=(char)(((c & 0x1F) << 6) |
                                                    (char2 & 0x3F));
                    break;
                case 14:
                    /* 1110 xxxx  10xx xxxx  10xx xxxx */
                    count += 3;
                    if (count > utflen)
                        throw new UTFDataFormatException(
                            "malformed input: partial character at end");
                    char2 = (intbytearr[count-2];
                    char3 = (intbytearr[count-1];
                    if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
                        throw new UTFDataFormatException(
                            "malformed input around byte " + (count-1));
                    chararr[chararr_count++]=(char)(((c     & 0x0F) << 12) |
                                                    ((char2 & 0x3F) << 6)  |
                                                    ((char3 & 0x3F) << 0));
                    break;
                default:
                    /* 10xx xxxx,  1111 xxxx */
                    throw new UTFDataFormatException(
                        "malformed input around byte " + count);
            }
        }
        // The number of chars produced may be less than utflen
        return new String(chararr, 0, chararr_count);
    }
New to GrepCode? Check out our FAQ X