Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
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 >> << >>...
(All of the following is to be written in Java) I have to build an application that will take as input XML documents that are, potentially, very large. The document is encrypted -- not with XMLsec, but with my client's preexisting encryption algorithm -- will be processed in three phases: First, the stream will be decrypted according to the aforementioned algorithm. Second, an extension cla...
I'm trying to do local IPC using Sockets and Object streams in Java however I'm seeing poor performance. I am testing the ping time of sending an object via an ObjectOutputStream to receiving a reply via an ObjectInputStream over a Socket. Here's the Requestor: public SocketTest(){ int iterations = 100; try { Socket socket = new Socket("localhost", 1212); ObjectInpu...
I have need for a "system" function call, the same as those in Python, Perl, PHP, Ruby, &c. It will be a component of a JavaScript standard library called Narwhal, when it's run on the Rhino JavaScript engine, which is in turn run on Java. The trouble is that Java's standard library appears to have abstracted away the ability to spawn a subprocess that shares the parent process's stdio. ...
Where is exactly is the demarkation between a version of Java and the JVM? I'm asking because of a recent 'educational' comment thread with a fellow SOpedian regarding the default buffer size of java.io.BufferedInputStream, which I see is 8192. (Has it always been 8192?) When thinking about just the API, it is clear to be what is what. But with the implementation of a java.* class...I jus...
I intend to use the markSupported feature for checking first byte to check the format then reset it, please tell me which stream should be used for tcp based communication in java. For most of the streams like datainputstream does not provide this feature. Please can give me some pointers to use mark and reset.
All, I have written a PhoneBook application in Java that is command line based. The application basically asks for some details of user like Name, Age, Address and phone numbers and stores them in a file. Other operations involve looking up PhoneBook by name, phone number etc. All the details are entered through console. I am trying to write JUnit test cases for each of the functionalities th...
I'm writing a program in java (already wrote a version in C too). I really need to put a character back to the input-stream after I read it. This can be accomplished by ungetc() in C/C++, and I was wonder how can I do the same thing in Java? For those of you don't know C/C++: char myc = (char)System.in.read(); and I check the value of myc and now I want to put back myc in to the System.in! so ...
I'm trying to do a VERY simple file upload. I want a Java FTPClient that can upload any file I tell it to. But the pdf always gets all messed up and my pdf editor (Adobe) won't open it, saying there is an I/O error. I'm using the following class: import org.apache.commons.net.ftp.FTPClient; .... FTPClient client = new FTPClient(); FileInputStream fis = null; try { ...
I'm dealing with the following code that is used to split a large file into a set of smaller files: FileInputStream input = new FileInputStream(this.fileToSplit); BufferedInputStream iBuff = new BufferedInputStream(input); int i = 0; FileOutputStream output = new FileOutputStream(fileArr[i]); BufferedOutputStream oBuff = new BufferedOutputStream...
I've got some code that: reads from a ReadableByteChannel into a ByteBuffer, takes note of the bytes transfered, pauses a few tens to hundreds of miliseconds, passes the ByteBuffer onto a WritableByteChannel. Some details: Both Channels are TCP/IP sockets. The total connection read size is in the tens of megabytes. The source socket (which the ReadableByteChannel is getting bytes f...
I have a 16mb binary file and I want to read bytes without using any loop. like if i want to read 16 byte i can pass 16 to some method(if there is any) and it give me my desired result... right now i am using loop for reading bytes but my application is so huge i am afraid that it do not get slow.kindly give me some hint. thanks alot.
I've looked at this every way I can think... The problem is that I end up writing the PERFECT number of bytes, and the files are VERY similar - but some bytes are different. I opened the Java generated file in Scite as well as the original, and even though they are close, they are not the same. Is there any way to fix this? I've tried doing everything possible - I've used different wrappers, re...
What I want to do is log the output from an inputstream that I go using org.apache.http.HttpEntity entity = response.getEntity(); org.apache.http.HttpResponse content =entity.getContent(); //Print the result to the screen for debugging //puroposes if(Logging.DEBUG) { InputStream content =entity.getContent(); int i; ...
I have read in wikipedia that Decorator pattern is used for .Net and Java IO classes. Can someone explain how this is being used? and what s the benefit of it with a possible example? There is an example of window forms on wiki but i wanted to know how it happens with IO classes.
I'm having an issue trying to parse the ascii part of a file, and once I hit the end tag, IMMEDIATELY start reading in the bytes from that point on. Everything I know in Java to read off a line or a whole word creates a buffer, which ruins any chance of getting the bytes immediately following my stop point. Is the only way to do this read in byte-by-byte, find new-lines, reconstruct everything ...
I have the following class subclass of FilterInputStream with only one method overrided. However the performance of this class is so poor. It performs at 1/10 the speed of its superclass. I even took the same source code from InputStream of javasrc and used it in my subclass. Same performance hit. Is there something wrong with overriding classes? public class NewLineStream extends FilterInputS...
Currently I'm trying to read a file in a mime format which has some binary string data of a png. In Windows, reading the file gives me the proper binary string, meaning I just copy the string over and change the extension to png and I see the picture. An example after reading the file in Windows is below: --fh-mms-multipart-next-part-1308191573195-0-53229 Content-Type: image/png;n...
InputStream data = realResponse.getEntity().getContent(); byte[] preview = new byte[100]; data.read(preview, 0, 100); // Now I want to refer to the InputStream later on, but I want it from the beginning of the stream, not 100 bytes in. I tried mark() it at 100, and then reset() after I read the first 100 bytes, but that doesn't work either. Any ideas? Probably a stupid mistake..just not se...
I want to prompt the user to begin entering characters and I want them to be able to enter characters as long as they want until they hit control+d to exit. For example, they can type a string of numbers like: 1234567 and as soon as they decide to hit control+d the line that they entered will be displayed (so without having to hit return) I am thinking I'll need a buffered reader or something...
Is there any possible way to create fileinputstream with mark supported feature as true ?
  /*
   * 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 BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

Author(s):
Arthur van Hoff
Since:
JDK1.0
 
 public
 
     private static int defaultBufferSize = 8192;

    
The internal buffer array where the data is stored. When necessary, it may be replaced by another array of a different size.
 
     protected volatile byte buf[];

    
Atomic updater to provide compareAndSet for buf. This is necessary because closes can be asynchronous. We use nullness of buf[] as primary indicator that this stream is closed. (The "in" field is also nulled out on close.)
 
     private static final
         AtomicReferenceFieldUpdater.newUpdater
         (BufferedInputStream.class,  byte[].class"buf");

    
The index one greater than the index of the last valid byte in the buffer. This value is always in the range 0 through buf.length; elements buf[0] through buf[count-1] contain buffered input data obtained from the underlying input stream.
 
     protected int count;

    
The current position in the buffer. This is the index of the next character to be read from the buf array.

This value is always in the range 0 through count. If it is less than count, then buf[pos] is the next byte to be supplied as input; if it is equal to count, then the next read or skip operation will require more bytes to be read from the contained input stream.

See also:
buf
 
     protected int pos;

    
The value of the pos field at the time the last mark method was called.

This value is always in the range -1 through pos. If there is no marked position in the input stream, this field is -1. If there is a marked position in the input stream, then buf[markpos] is the first byte to be supplied as input after a reset operation. If markpos is not -1, then all bytes from positions buf[markpos] through buf[pos-1] must remain in the buffer array (though they may be moved to another place in the buffer array, with suitable adjustments to the values of count, pos, and markpos); they may not be discarded unless and until the difference between pos and markpos exceeds marklimit.

See also:
mark(int)
pos
    protected int markpos = -1;

    
The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail. Whenever the difference between pos and markpos exceeds marklimit, then the mark may be dropped by setting markpos to -1.

    protected int marklimit;

    
Check to make sure that underlying input stream has not been nulled out due to close; if not return it;
    private InputStream getInIfOpen() throws IOException {
        InputStream input = ;
        if (input == null)
            throw new IOException("Stream closed");
        return input;
    }

    
Check to make sure that buffer has not been nulled out due to close; if not return it;
    private byte[] getBufIfOpen() throws IOException {
        byte[] buffer = ;
        if (buffer == null)
            throw new IOException("Stream closed");
        return buffer;
    }

    
Creates a BufferedInputStream and saves its argument, the input stream in, for later use. An internal buffer array is created and stored in buf.

Parameters:
in the underlying input stream.
    public BufferedInputStream(InputStream in) {
        this(in);
    }

    
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use. An internal buffer array of length size is created and stored in buf.

Parameters:
in the underlying input stream.
size the buffer size.
Throws:
java.lang.IllegalArgumentException if size <= 0.
    public BufferedInputStream(InputStream inint size) {
        super(in);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
         = new byte[size];
    }

    
Fills the buffer with more data, taking into account shuffling and other tricks for dealing with marks. Assumes that it is being called by a synchronized method. This method also assumes that all data has already been read in, hence pos > count.
    private void fill() throws IOException {
        byte[] buffer = getBufIfOpen();
        if ( < 0)
             = 0;            /* no mark: throw away the buffer */
        else if ( >= buffer.length)  /* no room left in buffer */
            if ( > 0) {  /* can throw away early part of the buffer */
                int sz =  - ;
                System.arraycopy(bufferbuffer, 0, sz);
                 = sz;
                 = 0;
            } else if (buffer.length >= ) {
                 = -1;   /* buffer got too big, invalidate mark */
                 = 0;        /* drop buffer contents */
            } else {            /* grow buffer */
                int nsz =  * 2;
                if (nsz > )
                    nsz = ;
                byte nbuf[] = new byte[nsz];
                System.arraycopy(buffer, 0, nbuf, 0, );
                if (!.compareAndSet(thisbuffernbuf)) {
                    // Can't replace buf if there was an async close.
                    // Note: This would need to be changed if fill()
                    // is ever made accessible to multiple threads.
                    // But for now, the only way CAS can fail is via close.
                    // assert buf == null;
                    throw new IOException("Stream closed");
                }
                buffer = nbuf;
            }
         = ;
        int n = getInIfOpen().read(bufferbuffer.length - );
        if (n > 0)
             = n + ;
    }

    
See the general contract of the read method of InputStream.

Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException if this input stream has been closed by invoking its close() method, or an I/O error occurs.
See also:
FilterInputStream.in
    public synchronized int read() throws IOException {
        if ( >= ) {
            fill();
            if ( >= )
                return -1;
        }
        return getBufIfOpen()[++] & 0xff;
    }

    
Read characters into a portion of an array, reading from the underlying stream at most once if necessary.
    private int read1(byte[] bint offint lenthrows IOException {
        int avail =  - ;
        if (avail <= 0) {
            /* If the requested length is at least as large as the buffer, and
               if there is no mark/reset activity, do not bother to copy the
               bytes into the local buffer.  In this way buffered streams will
               cascade harmlessly. */
            if (len >= getBufIfOpen().length &&  < 0) {
                return getInIfOpen().read(bofflen);
            }
            fill();
            avail =  - ;
            if (avail <= 0) return -1;
        }
        int cnt = (avail < len) ? avail : len;
        System.arraycopy(getBufIfOpen(), boffcnt);
         += cnt;
        return cnt;
    }

    
Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

This method implements the general contract of the corresponding read method of the InputStream class. As an additional convenience, it attempts to read as many bytes as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true:

  • The specified number of bytes have been read,
  • The read method of the underlying stream returns -1, indicating end-of-file, or
  • The available method of the underlying stream returns zero, indicating that further input requests would block.
If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of bytes actually read.

Subclasses of this class are encouraged, but not required, to attempt to read as many bytes as possible in the same fashion.

Parameters:
b destination buffer.
off offset at which to start storing bytes.
len maximum number of bytes to read.
Returns:
the number of bytes read, or -1 if the end of the stream has been reached.
Throws:
IOException if this input stream has been closed by invoking its close() method, or an I/O error occurs.
    public synchronized int read(byte b[], int offint len)
        throws IOException
    {
        getBufIfOpen(); // Check for closed stream
        if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
        int n = 0;
        for (;;) {
            int nread = read1(boff + nlen - n);
            if (nread <= 0)
                return (n == 0) ? nread : n;
            n += nread;
            if (n >= len)
                return n;
            // if not closed but no bytes available, return
            InputStream input = ;
            if (input != null && input.available() <= 0)
                return n;
        }
    }

    
See the general contract of the skip method of InputStream.

Throws:
IOException if the stream does not support seek, or if this input stream has been closed by invoking its close() method, or an I/O error occurs.
    public synchronized long skip(long nthrows IOException {
        getBufIfOpen(); // Check for closed stream
        if (n <= 0) {
            return 0;
        }
        long avail =  - ;
        if (avail <= 0) {
            // If no mark position set then don't keep in buffer
            if ( <0)
                return getInIfOpen().skip(n);
            // Fill in buffer to save bytes for reset
            fill();
            avail =  - ;
            if (avail <= 0)
                return 0;
        }
        long skipped = (avail < n) ? avail : n;
         += skipped;
        return skipped;
    }

    
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

This method returns the sum of the number of bytes remaining to be read in the buffer (count - pos) and the result of calling the in.available().

Returns:
an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking.
Throws:
IOException if this input stream has been closed by invoking its close() method, or an I/O error occurs.
    public synchronized int available() throws IOException {
        return getInIfOpen().available() + ( - );
    }

    
See the general contract of the mark method of InputStream.

Parameters:
readlimit the maximum limit of bytes that can be read before the mark position becomes invalid.
See also:
reset()
    public synchronized void mark(int readlimit) {
         = readlimit;
         = ;
    }

    
See the general contract of the reset method of InputStream.

If markpos is -1 (no mark has been set or the mark has been invalidated), an IOException is thrown. Otherwise, pos is set equal to markpos.

Throws:
IOException if this stream has not been marked or, if the mark has been invalidated, or the stream has been closed by invoking its close() method, or an I/O error occurs.
See also:
mark(int)
    public synchronized void reset() throws IOException {
        getBufIfOpen(); // Cause exception if closed
        if ( < 0)
            throw new IOException("Resetting to invalid mark");
         = ;
    }

    
Tests if this input stream supports the mark and reset methods. The markSupported method of BufferedInputStream returns true.

Returns:
a boolean indicating if this stream type supports the mark and reset methods.
See also:
InputStream.mark(int)
InputStream.reset()
    public boolean markSupported() {
        return true;
    }

    
Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

Throws:
IOException if an I/O error occurs.
    public void close() throws IOException {
        byte[] buffer;
        while ( (buffer = ) != null) {
            if (.compareAndSet(thisbuffernull)) {
                InputStream input = ;
                 = null;
                if (input != null)
                    input.close();
                return;
            }
            // Else retry in case a new buf was CASed in fill()
        }
    }
New to GrepCode? Check out our FAQ X