Storing input stream in a buffer

Hi, what is the best way to read an input stream and save it into a buffer?
Thanks,
Andrea

Not sure if any of the following are an improvement or not. But here are just a few thoughts. Why handle all the byte array allocation yourself? IMO, it would be easier to simply use a ByteArrayOutputStream at that point. The listeners can call toByteArray() and be passed an offset and length of what was read.
Now that I think about it, you could probably make it a bit more generic even than that. For example, here is a class I end up using all the time:
public final class Pipe
    /** Buffer size to read in and output. */
    private static final int DEFAULT_BUFFER_SIZE = 2048;
     * Private constructor.  Use public static facade methods instead.
    private Pipe()
        super();
     * Pipes the specified binary data to the specified output stream.
     * @param   target                      Binary data to output
     * @param   out                         Stream to write
     * @throws  IOException
    public static final void pipe(final byte[] target, final OutputStream out)
        throws IOException
        assert (target != null) : "Missing byte array";
        assert (out != null) : "Missing output stream";
        pipe(new ByteArrayInputStream(target), out, true);
     * Reads from the specified input stream and returns all data as an in-memory.
     * binary array.  Note:  Since streams may be of any arbitrary size, this
     * method requires that you wrap your original stream in a {@link FiniteInputStream}.
     * Please ensure that this method is only used to read in data under, say, 2mB.
     * @param   in                          Stream to read
     * @return  byte[]                      Binary data read
     * @throws  IOException
    public static final byte[] pipe(final FiniteInputStream in)
        throws IOException
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        pipe(in, byteOut, true);
        return byteOut.toByteArray();
     * Reads from the specified input stream and outputs immediately to the specified.
     * output stream.  <br>
     * <br>
     * If you have any confusion about which <code>Pipe</code> method to use, choose
     * this one.  It has the lowest memory overhead and is the most efficient.  Always
     * choose this method when streaming large amounts of data or content.
     * @param   in                          Input stream to read
     * @param   out                         Output stream to write
     * @param   close                       Close both stream if true
     * @return  long                        Byte count piped
     * @throws  IOException
    public static final long pipe(final InputStream in, final OutputStream out, final boolean close)
        throws IOException
        assert (in != null) : "Missing input stream";
        assert (out != null) : "Missing output stream";
        long bytesPiped = 0L;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        try
            int bytesRead = in.read(buffer);
            while (bytesRead >= 0)
                if (bytesRead > 0)
                    out.write(buffer, 0, bytesRead);
                    bytesPiped = bytesPiped + bytesRead;
                bytesRead = in.read(buffer);
            out.flush();
            return bytesPiped;
        finally
            if (close)
                IoHelper.close(in);
                IoHelper.close(out);
}You simply could add the listener feature (which I do think is useful and elegant). Note the FiniteInputStream and FiniteOutputStream are just sub-classes of FilterInputStream and FilterOutputStream that allow you to limit how many bytes are piped, if desired.
- Saish

Similar Messages

  • Buffered Input stream that increases internal buffer dynamically

    I need to parse an input stream until I find a <META> tag with character encoding. I then need to reset to the beginning of the input stream and start parsing the stream again with the correct character encoding.
    BufferedInputStream provides mark() and reset() methods which can be used to accomplish this task. However, the input stream data can be 1MB size and the only way I can think of forcing the BufferedInputStream to hold that content size is by specifying the size during construction.
    I don't want to initialize the content size during construction of the BufferedStream for every data file I parse because some documents could have the tag in the beginning of the file and it could be waste of memory.
    Question: Is there already a class which allows to set the maximum buffer size and which grows gradually to that size rather than during construction.
    Thanks for any help.

    DrClap, I connect to a webserver and request a file. I just use the InputStream returned by the HttpResponse object to read the file. So, the answer to your question is I can't close and reopen the file.
    Jawahar

  • Playing input stream audio in j2me

    want to make a text-to-speech synthesizer for mobile phones.
    for that i am using FreeTTS (text-to-speech synthesizer written in java)
    so i have made a client-server model where i have a midp client which is sending text to the FreeTTS acting as a server.... for this i am using socket...
    so basically -- client is sending text to server -- server processes the text and sends the audio stream back to client
    the problem is i dont know how to play the audio stream received on client side
    i tried to copy it in a buffer but its not working..
    do i need to save the file in some format before playing it?
    or can the player play the audio stream directly?
    this is how i am copying the contents in the buffer
    try
    InputStream is = socketConnection.openInputStream();
    byte[] buff = new byte[1024];
    int bytesIn = is.read(buff, 0, 1024);
    ByteArrayInputStream bis = new ByteArrayInputStream(buff);
    player = Manager.createPlayer(bis, "audio/x-wav" );
    player.start();
    but it gives an error saying
    javax.microedition.media.MediaException: Malformed wave media
    i tried to display the contents of bis on console it reads
    java.io.ByteArrayInputStream@d590dbc
    i tried the same with the Free TTS client and got the same output.
    so i think client socket is even receiving the audio stream properly...however, im not sure.
    is the whole client-server using socket idea correct?
    if yes, please tell me how to play this audio stream in j2me (the client)
    if it is wrong then please tell me a correct way to do this.
    can the input stream be stored as a WAV file and then played? if yes, then how can i store it as a WAV file? Can this be achieved by appending a WAV header?

    I once tried the similar thing, I ended up buffer all the content locally (from bluetooth), then play the wave file.
    Maybe someone else has better idea.

  • IOException: Connection reset by peer: JVM_recv in socket input stream read

    hi
    I encountered a problem : a program throw out an exception:java.io.IOException: Io exception:
    Connection reset by peer: JVM_recv in socket input stream read.
    I tried my best to resolve it ,but unfortunately,i didn't know what caused the exception.
    the following is my application environment:
    I have two PC(Win2000os),one is a server which installed oracle9.2.0.2 and jdeveloper9.0.3,the another is a
    client which only intalled jdeveloper9.0.3.Two days ago,i performed a web application on my client with
    jdeveloper,and it includes some JSP and a javabean files.JSP Page finished uploading client xml file to a
    folder on server and the javabean finished loading the xml file into a xmltype column.I can make sure the
    connection is established and the javabean is OK,beacause my some jsp page can successfully use
    <jsp:usebean> tag and use the javabean's some other public interfaces,except the interface that finishs
    loading the xml file into a xmltype(clob) column.
    Then i do many tests!I changed the javabean to a java class incluse a main method beacause it is easy to
    debug.Finally i found the following code caused the exception:
    public CLOB writetoClob( CLOB clob, InputStream is )throws SQLException, IOException {
    InputStreamReader reader = new InputStreamReader( is );
    Writer writer = clob.getCharacterOutputStream( );
    char[] buffer = new char[clob.getChunkSize(  )];
    int charsRead;
    for ( charsRead = reader.read( buffer ); charsRead > -1;charsRead = reader.read( buffer ) ) {
    writer.write( buffer, 0, charsRead );
    writer.close();
    return clob;
    when it runs to writer.close(),the exception is caused!
    Then i copy the java class to the server,it runs ok!
    That is to say ,the same code,the different result!
    But when i run my web application on server with jdeveloper Embedded OC4J Server and a jsp page loaded javabean
    and run to mentioned code ,the same exception occured!
    I checked the application log in event viewer,the descriptions was:
    The data buffer created for the "AppleTalk" service in the "C:\WINNT\system32\atkctrs.dll" library is not
    aligned on an 8-byte boundary. This may cause problems for applications that are trying to read the
    performance data buffer. Contact the manufacturer of this library or service to have this problem corrected or
    to get a newer version of this library.
    I search some some resolution about this exception with web and someone sayed :
    This basically means that a network error occurred while the client was receiving data from the server. But
    what is really happening is that the server actually accepts the connection, processes the request, and sends a
    reply to the client. However, when the server closes the socket, the client believes that the connection has
    been terminated abnormally because the socket implementation sends a TCP reset segment telling the client to
    throw away the data and report an error.
    Sometimes, this problem is caused by not properly closing the input/output streams and the socket connection.
    Make sure you close the input/output streams and socket connection properly. If everything is closed properly,
    however, and the problem persists, you can work around it by adding Thread.sleep(1000) before closing the
    streams and the socket. This technique, however, is not reliable and may not work on all systems.
    In general,the following information is conclution:
    Web application runs error both on client and on server.
    If it was changed to a client java class,it only run ok on server!
    i have done anything that i can do now,i feel depressed very much!
    how can i resolve the problem!
    Any a little help will be appreciated!
    regards!
    Thanks
    Jiawei ZHAO

    How can i solve the problem.
    Thanks in advance!
    Jiawei Zhao

  • Open an input stream to a socket

    How many times I can open an input stream to a socket? If I create more than one an input stream to a socket, does this affect anything?
    Thanks.

    Generally low level classes do not have high level logic. Socket is a low level class, it's only logic is to connect you to something, and allow you to read and write to that thing (through the socket) using streams. Being able to connect multiple times or setting marks on your stream is a higher level of logic. Putting to much logic is low level classes tends to reduce re-useablility (making unmarkable streams markable as nothing to do with sockets and can be re-used upon any streams that do not support to be marked) and sometimes performances (having marks means having a buffer means having a potential big memory allocation in your Socket that you do not control).
    So in your case, since you are not really interested in re-connecting a socket, you should rather go for a wrapping InputStream that provides marking capabilities over the streams used by the socket class itself.
       Socket socket = getSocket();
       // this one does not support to be marked
       InputStream stream = socket.getInputStream();
       // but now it does :)
       stream = new BufferedInputStream( stream );

  • Output/Input Streams Cannot Resolve Symbol..

    It is missing something, how do I declare the below 2 variables?
         //Get streams to send and receive data
         private void getSockStreams() throws IOException {
              //Set up output streams for objects
              output = new ObjectOutputStream(connection.getOutputStream());
              output.flush(); //Flush output buffer to send header information.
              //Set up input stream for objects.
              input = new ObjectInputStream(connection.getInputStream());
              displayMessage("Got I/O Streams");
         }Error:
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:74: cannot resolve symbol
    symbol  : variable output
    location: class appinterface
                    output = new ObjectOutputStream(connection.getOutputStream());
                    ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:75: cannot resolve symbol
    symbol  : variable output
    location: class appinterface
                    output.flush(); //Flush output buffer to send header information.
                    ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\appinterface.java:78: cannot resolve symbol
    symbol  : variable input
    location: class appinterface
                    input = new ObjectInputStream(connection.getInputStream());
                    ^
    3 errors
    Process completed.

    Same way you declare any variables in Java:ObjectOutputSream output;
    output = ....
    OR
    ObjectOutputStream output = ...

  • GZIP compressing input stream?

    I have an API which takes an InputStream for feeding in large binary data.
    Suppose I want to write a wrapper around that API which GZIPs the data on the fly. This would require some kind of InputStream which will compress the data with GZIP on the fly. However, GZIPInputStream can only decompress on the fly.
    Does anyone know of a way to do the exact opposite?

    So, don't store the entire file in memory. Storing a compressed version of the file isn't much of a
    solution.You're not paying attention. I said I can't FIT the data in memory. If I can't fit it in memory, why would I be trying to store it in memory? Hence why I want to store it in a DATABASE.
    If you can't grasp the most simple of uses for a database, there isn't a lot of hope for you in this field in the future.
    You actually can use a ByteArrayOutputStream, to generate the compressed bytes, as I described, > but you apparently we're paying attention, which at this point is all I expect from you.Okay, how? If I simply put all the uncompressed bytes into the GZIPOutputStream and that output stream is attached to the ByteArrayOutputStream, I will run out of memory.
    Code, please. In other words, prove that what you say is possible.
    You are allowed to. It's debatable whether it's a good idea. Anyway this is the first time you
    mentioned JDBC. Back when we wanted to help you (before you called us idiots) that might
    have been useful information. It's easier to help people when you have information about what
    the hell theyr'e trying to do.I did say that we have an API which takes an input stream, and that this was the reason why I had to pass in an input stream. It doesn't matter whether it's JDBC, or anything else. What is important is that it takes an input stream.
    Actually, it's pretty cheap. It's probably cheaper than the cost of the extra RAM you'll need doing
    extraneous compression/decompression.Actually, compression is generally fairly inexpensive, RAM-wise. You lose some CPU, but CPU is even cheaper than the amounts of disk space which we would otherwise need for this.
    We're storing gigabytes of data, and
    I would rather not have to actually store gigabytes
    of data.So, you're not actually storing it now?We're storing it compressed, which makes it take less space. You do know what compression is, right?
    A redesign might end up removing GZIP entirely. But maybe not. It's hard to say because you still
    haven't given a lot of details, and given your attitude I'm certain your estimation of the project is
    entirely wrong anyway. At this point I don't care either way. Good luck with your project to create
    an unmaintainable buggy monstrosity.Actually, this is trying to make the project more maintainable. Right now, we have multiple components each doing the gzipping in their own sections. I'm trying to make a component which can generically take a data stream, and store it into the database compressed.
    You're partially right, though. A redesign would remove GZIP entirely -- I would use Deflate as-is. Deflate has convenient methods for working with smaller chunks of data, and I could borrow much of the code from InflateInputStream and modify it to create DeflateInputStream. The next version of our app, once we're willing to break compatibility, will probably do this.

  • Cached input stream?

    the problem i got is that i got a lot of processes reading the same amount of bytes (6k) from disk at the same time. this will lead to the point where the IO starts blocking since it has to serve too much at once. a solution would be rading out larger chunks at once (like 100k) using something like a CachedImputStream. the CachedInputStream could be chained with a normal InputStream that reads the 6k out of it. this way the disks searches could be reduced a lot.
    i was wondering if there is something like a cached input stream for java already or if i have to wirte one by myself? (note: a BufferedInputStream wouldn't solve the problem since it only tries to keep the buffer full in memory - i can't specify how many bytes to read from disk at once)

    i can't specify how many bytes to read from disk at onceDo you mean the following method does not work?
    read(byte[] bytes, int start, int length)?
    You will probibly find that the OS reads a fixed size e.g. 8K, 16K, 32K or 64K depending on the block size of the disk regardles sof what you set. Using this option reduced the number of calls from your program to the OS, how the OS accesses the disk cannot be controlled in Java. (Your program can only provide a hint)
    If performance is an issue, either reduce the number of concurrent requests or use higher performing disks such as SCSI or multiple SCSI drives mirrored/stripped.

  • Unexpected end of ZLIB input stream error while compiling

    Hello
    I am getting errors when i run RMIC and JAR apps in the same window, i've tried to close and open the input stream in between, tried delaying between the two , tried /I paramaeter, any one ?
    Rmic stage pass OK
    but i get Unexpected end of ZLIB input stream exception i some of the file on the jar stage :
    Main batch :
    start /B %SWIFT_LOCAL_HOME%\scripts\rmicAll.bat
    start /B %SWIFT_LOCAL_HOME%\scripts\create_jar.bat
    Jar exception :
    adding: CVS/(in = 0) (out= 0)(stored 0%)
    adding: CVS/Entries(in = 383) (out= 168)(deflated 56%)
    adding: CVS/Repository(in = 13) (out= 15)(deflated -15%)
    adding: CVS/Root(in = 60) (out= 60)(deflated 0%)
    java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:223)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:146)
    at sun.tools.jar.Main.update(Main.java:508)
    at sun.tools.jar.Main.run(Main.java:184)
    at sun.tools.jar.Main.main(Main.java:1022)
    C:\Eclipse_Workspace\Swift\scripts>date /T 1>>C:\Eclipse_Workspace\Swift\swift_build.txt
    C:\Eclipse_Workspace\Swift\scripts>time /T 1>>C:\Eclipse_Workspace\Swift\swift_build.txt
    C:\Eclipse_Workspace\Swift\scripts>echo Swift.jar Build Time : 1>C:\Eclipse_Workspace\Swift\swift_build.txt
    C:\Eclipse_Workspace\Swift\scripts>"C:\Program Files\Java\jdk1.6.0_02\bin\jar" -uvf C:\Eclipse_Workspace\Swift\jars\swift.jar -C C:\Eclipse_Workspace\Swift swift_build.txt
    java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:223)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:141)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:146)
    at sun.tools.jar.Main.update(Main.java:508)
    at sun.tools.jar.Main.run(Main.java:184)
    at sun.tools.jar.Main.main(Main.java:1022)

    You seem to be adding the contents of CVS directories to the jar file. CVS directories contain internal information used by CVS. This suggests to me that you are either deliberately doing something really really strange, or you are doing something stupid out of ignorance.
    The CVS directories suggest you are making a jar from your source code. Generally you compile the source code 'tree' and place the output (.class files etc) in another tree and create the jar from that second tree.
    And PaulMiner is correct, you'll definitely need to change 'start' to 'call'. Do that first, then take a look at what is source code, and what it is that you want in your jar file and make sure it is all sensible, I suspect it isn't.

  • Is this the best way to measure the speed of an input stream?

    Hi guys,
    I have written the following method to read the source of a web page. I have added the functionality to calculate the speed.
    public StringBuffer read(String url)
            int lc = 0;
            long lastSpeed = System.currentTimeMillis();
            //string buffer for reading in the characters
            StringBuffer buffer = new StringBuffer();
            try
                //try to set URL
                URL URL = new URL(url);
                //create input streams
                InputStream content = (InputStream) URL.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(content));
                //in line
                String line;
                //while still reading in
                while ((line = in.readLine()) != null)
                    lc++;
                    if ((lc % _Sample_Rate) == 0)
                        this.setSpeed(System.currentTimeMillis() - lastSpeed);
                        lastSpeed = System.currentTimeMillis();
                    //add character to string buffer
                    buffer.append(line);
            //catch errors
            catch (MalformedURLException e)
                System.out.println("Invalid URL - " + e);
            catch (IOException e)
                System.out.println("Invalid URL - " + e);
            //return source
            return buffer;
        }Is it faster to read bytes rather than characters?
    This method is a very important part of my project and must be as quick as possible.
    Any ideas on how I can make it quicker? Is my approach to calculating the speed the best way to it?
    Any help/suggestions would be great.
    thanks
    alex

    sigh
    reading bytes might be slightly faster than reading chars, since you don't have to do the conversion and you don't have to make String objects. Certainly, you don't want to use readLine. If you're using a reader, use read(buf, length, offset)
    My suggestion:
    Get your inputstream, put a bufferedInputStream over it, and use tje loadAll method from my IOUtils class.
    IOUtils is given freely, but please do not change its package or submit this as your own work.
    ====
    package tjacobs;
    import java.awt.Component;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JOptionPane;
    public class IOUtils {
         public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
         public static final int DEFAULT_WAIT_TIME = 30 * 1000; // 30 Seconds
         public static final int NO_TIMEOUT = -1;
         public static final boolean ALWAYS_BACKUP = false;
         public static String loadTextFile(File f) throws IOException {
              BufferedReader br = new BufferedReader(new FileReader(f));
              char data[] = new char[(int)f.length()];
              int got = 0;
              do {
                   got += br.read(data, got, data.length - got);
              while (got < data.length);
              return new String(data);
         public static class TIMEOUT implements Runnable {
              private long mWaitTime;
              private boolean mRunning = true;
              private Thread mMyThread;
              public TIMEOUT() {
                   this(DEFAULT_WAIT_TIME);
              public TIMEOUT(int timeToWait) {
                   mWaitTime = timeToWait;
              public void stop() {
                   mRunning = false;
                   mMyThread.interrupt();
              public void run () {
                   mMyThread = Thread.currentThread();
                   while (true) {
                        try {
                             Thread.sleep(mWaitTime);
                        catch (InterruptedException ex) {
                             if (!mRunning) {
                                  return;
         public static InfoFetcher loadData(InputStream in) {
              byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
              return loadData(in, buf);
         public static InfoFetcher loadData(InputStream in, byte buf[]) {
              return loadData(in, buf, DEFAULT_WAIT_TIME);
         public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
              return new InfoFetcher(in, buf, waitTime);
         public static String loadAllString(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              return new String(fetcher.buf, 0, fetcher.got);
         public static byte[] loadAll(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              byte bytes[] = new byte[fetcher.got];
              for (int i = 0; i < fetcher.got; i++) {
                   bytes[i] = fetcher.buf;
              return bytes;
         public static class PartialReadException extends RuntimeException {
              public PartialReadException(int got, int total) {
                   super("Got " + got + " of " + total + " bytes");
         public static class InfoFetcher implements Runnable {
              public byte[] buf;
              public InputStream in;
              public int waitTime;
              private ArrayList mListeners;
              public int got = 0;
              protected boolean mClearBufferFlag = false;
              public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
                   this.buf = buf;
                   this.in = in;
                   this.waitTime = waitTime;
              public void addInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        mListeners = new ArrayList(2);
                   if (!mListeners.contains(fll)) {
                        mListeners.add(fll);
              public void removeInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        return;
                   mListeners.remove(fll);
              public byte[] readCompletely() {
                   run();
                   return buf;
              public int got() {
                   return got;
              public void run() {
                   if (waitTime > 0) {
                        TIMEOUT to = new TIMEOUT(waitTime);
                        Thread t = new Thread(to);
                        t.start();
                   int b;
                   try {
                        while ((b = in.read()) != -1) {
                             if (got + 1 > buf.length) {
                                  buf = expandBuf(buf);
                             buf[got++] = (byte) b;
                             int available = in.available();
                             if (got + available > buf.length) {
                                  buf = expandBuf(buf);
                             got += in.read(buf, got, available);
                             signalListeners(false);
                             if (mClearBufferFlag) {
                                  mClearBufferFlag = false;
                                  got = 0;
                   } catch (IOException iox) {
                        throw new PartialReadException(got, buf.length);
                   } finally {
                        buf = trimBuf(buf, got);
                        signalListeners(true);
              private void setClearBufferFlag(boolean status) {
                   mClearBufferFlag = status;
              public void clearBuffer() {
                   setClearBufferFlag(true);
              private void signalListeners(boolean over) {
                   if (mListeners != null) {
                        Iterator i = mListeners.iterator();
                        InputStreamEvent ev = new InputStreamEvent(got, buf);
                        //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                        while (i.hasNext()) {
                             InputStreamListener fll = (InputStreamListener) i.next();
                             if (over) {
                                  fll.gotAll(ev);
                             } else {
                                  fll.gotMore(ev);
         public static interface InputStreamListener {
              public void gotMore(InputStreamEvent ev);
              public void gotAll(InputStreamEvent ev);
         public static class InputStreamEvent {
              public int totalBytesRetrieved;
              public byte buffer[];
              public InputStreamEvent (int bytes, byte buf[]) {
                   totalBytesRetrieved = bytes;
                   buffer = buf;
              public int getBytesRetrieved() {
                   return totalBytesRetrieved;
              public byte[] getBytes() {
                   return buffer;
         public static void copyBufs(byte src[], byte target[]) {
              int length = Math.min(src.length, target.length);
              for (int i = 0; i < length; i++) {
                   target[i] = src[i];
         public static byte[] expandBuf(byte array[]) {
              int length = array.length;
              byte newbuf[] = new byte[length *2];
              copyBufs(array, newbuf);
              return newbuf;
         public static byte[] trimBuf(byte[] array, int size) {
              byte[] newbuf = new byte[size];
              for (int i = 0; i < size; i++) {
                   newbuf[i] = array[i];
              return newbuf;

  • Reset input stream

    Is there any way to mark/reset (or something comparable) an input stream that does not support the actual mark/reset methods? I'm using a DataInputStream, which contains a FileInputStream, and I've gotten an IOException saying mark/reset is not supported. Is there any other way to do it?

    I'm basically just reading bytes of binary data from a file, and I want to include a feature to reset and start reading again from the beginning. here's some of my code:
    public static void readWithDelay() {
            byte buf[] = new byte[100000];
            byte skipbytes[] = new byte[2];
            int length = 0, prevtime, time, lastprevtime=0, num=0, timecheck,skiplength=0;
            long period, filesize=0, bytecount = 0;
            double val = 0.0;
            try {
                begin = System.currentTimeMillis();
                // open the .pgem file stream
                try {
                    binfile = new DataInputStream(new FileInputStream(getFname()));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(new JFrame(), "File not Found. Try Again.", "Open File error", JOptionPane.ERROR_MESSAGE);
                try {
                    File file = new File(getFname());
                    filesize = file.length();
                } catch (Exception e) {
                    e.printStackTrace();
                try {
                    // open the socket to socket on localhost
                    Socket socket = new Socket(getText(), port);  // 1222 is TagBrowsers port
                    socket.setTcpNoDelay(true); // Disable TCP Nagle algorithm
                    socketOutputStream = new DataOutputStream(socket.getOutputStream());
                } catch (UnknownHostException u) {
                    JOptionPane.showMessageDialog(new JFrame(), "Host Not Found. Defaulting to localhost", "Socket error", JOptionPane.ERROR_MESSAGE);
                    Socket socket = new Socket("localhost", 1222);  // 1222 is TagBrowsers port
                    socket.setTcpNoDelay(true); // Disable TCP Nagle algorithm
                    socketOutputStream = new DataOutputStream(socket.getOutputStream());
                bos = new BufferedOutputStream(socketOutputStream, 10000);
                // loop copying file to output buffer until endfile
                rate=rate/10;
                start();
                begin = System.currentTimeMillis();
                //binfile.mark(500000000); <<<<<Tried to mark it here>>>>
                for (int i=0;i<24;i++) {
                    buf[i] = binfile.readByte();
                    bytecount++;
                time = ((buf[6] & 0xff) << 24) | ((buf[7] & 0xff) << 16) | ((buf[8] & 0xff) << 8) | (buf[9] & 0xff);
                length = ((buf[14] & 0xff) << 8) | (buf[15] & 0xff);
                for (int i=24;i<24+length;i++) {
                    buf[i] = binfile.readByte();
                    bytecount++;
                prevtime = time;
                try {                       // While !end of file
                    while (true && !stopXfer) {
                        while (prevtime == time) {
                            while (pause)
                                Thread.sleep(15);
                            bos.write(buf,0,24 + length);
                            prevtime = time;
                            for (int i=0;i<24;i++) {
                                buf[i] = binfile.readByte();
                                bytecount++;
                            time = ((buf[6] & 0xff) << 24) | ((buf[7] & 0xff) << 16) | ((buf[8] & 0xff) << 8) | (buf[9] & 0xff);
                            length = ((buf[14] & 0xff) << 8) | (buf[15] & 0xff);
                            for (int i=24;i<24+length;i++) {
                                buf[i] = binfile.readByte();
                                bytecount++;
                          /*  if (rewind) {
                                binfile.reset();    <<<<Reset here>>>>>
                                rewind = false;
                            while (fastforward) {
                                binfile.skip(14);
                                bytecount+=24;
                                skipbytes[0] = binfile.readByte();
                                skipbytes[1] = binfile.readByte();
                                skiplength = ((skipbytes[0] & 0xff) << 8) | (skipbytes[1] & 0xff);
                                binfile.skip(8+skiplength);
                                bytecount+=10+length;
                                val = (double)(bytecount)/(double)(filesize);
                                updateDelayProgress((int)(val*100));
                                //System.out.println(bytecount);
                            // if times are out of order, flush buffer right away
                            if (time < prevtime || time==lastprevtime) {
                                period = 0;
                                bos.flush();
                                timecheck = prevtime;
                                prevtime = time;
                        if (lastprevtime > prevtime)
                            prevtime = lastprevtime;
                        period = (long) (time - prevtime);
                        try {
                            bos.flush();
                            stop();
                            if (period < elapsedTime || period > 750)
                                period=elapsedTime;
                            val = (double)(bytecount)/(double)(filesize);
                            updateDelayProgress((int)(val*100));
                            Thread.sleep((int)(rate*(period - elapsedTime)));
                            reset();
                            start();
                        } catch(InterruptedException ie){
                            System.out.println("Problem with thread");
                            System.exit(1);
                        prevtime = time;
                        lastprevtime = time;
                        timecheck = time;
                } catch (EOFException e) {
                } catch (SocketException s) {
                    System.out.println("Transmission ended");
                } catch (Exception e) {
                    e.printStackTrace();
                // Close input stream and display dialog with total duration of the read and transfer
                try {
                    minutes = (((System.currentTimeMillis() - begin)/1000) / 60);
                    seconds = (((System.currentTimeMillis() - begin)/1000) % 60);
                    binfile.close();
                    bos.close();
                    JOptionPane.showMessageDialog(new TBCGUI(), "Read completed in " + minutes + " minutes, " + seconds + " seconds");
                    getFrame().validate();
                } catch (Exception e) {
                    System.err.println(e);
                    e.printStackTrace();
            } catch (Exception e) {}
        }

  • How do I return an input stream from a text file

    Suppose there's a class with methods..
    one of the methods is something like..
    public int value() and has a return statement at the end obviously for returning an int value..
    Another method reads a text file and creates an input stream..
    Scanner data  = new Scanner(new File(input.next()));
    I want to return the data when I do a call to this method, but I'm not sure what the method heading would look like..

    flounder wrote:
    Are we supposed to magically know what those errors are? Do you think that copying and pasting the exact error messages and indicating the lines they occur on would be useful to us?Sorry about that..
    I've replicated the same code below; and put the number of the line where the error is.
    +cannot find symbol variable read     [line 21]+
    +cannot find symbol variable read     [line 23]+
    +cannot find symbol variable read     [line 29]+
    +cannot find symbol variable read     [line 31]+
    +cannot find symbol variable inputStream     [line 44]+
    +calculate() in textInput cannot be applied to (java.util.Scanner)     [line 57]+
    the reason I have the _______ for the createInputStream() method is because I'm not really sure what the heading type should be to return the input stream.
    import java.io.*;
    import java.util.*;
    public class textInput
              public void requestFileName()
                   Scanner input = new Scanner(System.in);
                   System.out.print("Enter file name: ");
              public _______ createInputStream() throws FileNotFoundException
                   Scanner input = new Scanner(System.in);
                   Scanner read = new Scanner(new File(input.next()));
                   return read;
              public void calculate() throws IOException
    21           double max;
                   double min;
    23            int count = 0;
                   double total = 0;
                   if (read.hasNextDouble())
                        double temp = read.nextDouble();
    29                 max = temp;
                        min = temp;
    31                 count++
                        total += temp;
                        while (read.hasNextDouble())
                             double current = read.nextDouble();
                             count++;
                             min = Math.min(current, min);
                             max = Math.max(current, max);
                             total += current;
                   System.out.println("Max of: " + max);
                   System.out.println("Min of: " + min);
    44            System.out.println("Average of " + total/count);
              public void close() throws IOException
                   inputStream.close();
              public static void main(String[] args)
                   textInput run = new textInput();
                   try
    57                 run.requestFileName();
                        run.createInputStream();
                        run.calculate();
                        run.close();
                   catch(FileNotFoundException e)
                        System.out.println("File not found.");
                        System.exit(0);
                   catch(IOException e)
                        System.out.prinln("File not found.");
                        System.exit(0);
    }

  • When using URLConnection read input stream error

    hi,
    In my applet I build a URLConnection, it connect a jsp file. In my jsp file I refer to a javaBean. I send two objects of request and response in jsp to javaBean. In javabean return output stream to URLConnect. At that time a error happened.WHY???(Applet-JSP-JAVABean)
    Thanks.
    My main code:
    APPLET:(TestApplet)
    URL url = new URL("http://210.0.8.120/jsp/test.jsp";
    URLConnection con;
    con = url .openConnection();
    con = servlet.openConnection();
    con.setDoInput( true );
    con.setDoOutput( true );
    con.setUseCaches( false );
    con.setRequestProperty( "Content-Type","text/plain" );
    con.setAllowUserInteraction(false);
    ObjectOutputStream out;
    out = new ObjectOutputStream(con.getOutputStream());
    Serializable[] data ={"test"};
    out.writeObject( data );
    out.flush();
    out.close();
    //until here are all rigth
    ObjectInputStream in = new ObjectInputStream( con.getInputStream() );//happened error
    JSP:
    TestBean testBean = new TestBean ();
    testBean .execute(request, response);
    JAVABEAN:
    public void execute( HttpServletRequest request,
    HttpServletResponse response )
    ObjectInputStream in = new ObjectInputStream( request.getInputStream() );
    String direct = (String) in.readObject();
    System.out.prinltn("direct");
    ObjectOutputStream out = new ObjectOutputStream( response.getOutputStream() );
    SerializableSerializable[] data ={"answer"};
    out.writeObject( data );
    out.flush();
    out.close();
    Error detail:
    java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:729)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:251)
         at TestApplet.postObjects(TestApplet.java:172)

    you have to pay attention to the sequence of opening the streams.
    The following example is: client sends a string to server, and servlet sends a response string back.
    client side:
             URL url = new URL( "http://152.8.113.149:8080/conn/servlet/test" );
             URLConnection conn = url.openConnection();   
             System.out.println( "conn: " + conn );
             conn.setDoOutput( true );
             conn.setDoInput( true );
             conn.setUseCaches( false );
             conn.setDefaultUseCaches (false);
             // send out a string
             OutputStream out = conn.getOutputStream();
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             oOut.writeObject( strSrc ); 
             // receive a string
             InputStream in = conn.getInputStream();     
             ObjectInputStream oIn = new ObjectInputStream( in );
             String strDes = (String)oIn.readObject();server side
             // open output stream
             OutputStream out = res.getOutputStream();  
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             // open input stream and read from client
             InputStream in  = req.getInputStream();
             ObjectInputStream oIn = new ObjectInputStream( in );
             String s = (String)oIn.readObject();
             System.out.println( s );
             // write to client
             oOut.writeObject( s + " back" ); I have the complete example at http://152.8.113.149/samples/app_servlet.html
    don't forget to give me the duke dollars.

  • Error while executing SSIS package - Error: 4014, Severity:20, State: 11. A fatal error occurred while reading the input stream from the network. The session will be terminated (input error: 109, output error: 0)

    Hi,
    We are getting the following error when running our SSIS packages on Microsoft SQL Server 2012 R2 on Windows Server 2008 R2 SP1:
    Error: 4014, Severity:20, State: 11.   A fatal error occurred while reading the input stream from the network. The session will be terminated (input error: 109, output error: 0)
    SQL Server Data Tools and SQL Server Database Engine reside on the same server.
    We tried the following:
    Disabling TCP Chimney Offload
    Installed Windows Server 2008 SP1
    Splitting our SSIS code into multiple steps so it is not all one large continuous operation
    The error occurs during a BulkDataLoad task.
    Other options we are investigating with the engineering team (out-sourced, so delayed responses):
    Firewall configurations (everything is local, so this should not make a difference)
    Disabling the anti-virus scanner
    Are there other things we can try?
    Any insight is greatly appreciated.
    Thanks!

    Hi HenryKwan,
    Based on the current information, the issue can be caused by many reasons. Please refer to the following tips:
    Install the latest hotfix based on your SQL Server version. Ps: there is no SQL Server 2012 R2 version.
    Change the MaxConcurrentExecutables property from -1 to another one based on the MAXDOP. For example, 8.
    Set "RetainSameConnection" Property to FALSE on the all the connection managers.
    Reference:
    https://connect.microsoft.com/SQLServer/feedback/details/774370/ssis-packages-abort-with-unexpected-termination-message
    If the issue is still existed, as Jakub suggested, please provide us more information about this issue.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Error in external tax system: SAX processing failed on input stream SAX pro

    Hi
    When I was posted in T.Code: FB70,  (Customer Invoice) I am getting below mentioned error.
    Error in external tax system: SAX processing failed on input stream SAX processi.
    I put tick mark on calculate Tax column and select O1(A/R Sales Taxable).
    Pls. help me.
    Thanks
    Ranjith

    Hi Ranjith,
    I also face this problem in Production now.
    Could you kindly share with me how you resolved this issue?
    Thanks,
    Markus

Maybe you are looking for

  • Apex giving installation problem on dell optiplex xe system

    Hi We have installed apex 4 on dell optiplex xe , but it display the source code when we use page forwared and backward of mozilla firefox. We also use the same versionon our laptpops and other non branded computer , it working fine. Regard Faiz

  • Merge InDesign, Illustrator and Photoshop together?

    Wouldn't it be great to have everything you need in one app? Actually, there are currently some applications like this. Take a look at DAWs. They deal with recorded audio (similar to bitmap) and MIDI (like vector) at the same time. And if you are loo

  • No (suitable) item found for purchase order

    Dear All, The order is stock transfer order (STO) item category U. i saw GR is already create. GI  and also DCGR. i want to do DCIR which is invoice receipt in tcode mr01, the error "No (suitable) item found for purchase order" is coming out. What wo

  • Remote queue in XI server for IBM MQSeries

    Dear All, my scenario is IBM MQSeries -> message via sender JMS adapter -> XI -> receiver RFC adapter -> R/3. now for IBM MQSeries to send a message to XI via a transmission queue in MQSeries - it needs a remote queue name and  queue  manager name in

  • Elements 11 Pixelated Photos

    I have elements 11 and whenever I try to zoom into the photo, it gets really pixelated really quickly and I'm not able to do very detailed editing.. Any suggestions on what I could do to fix that? (Using Windows 8) ps.. I also have PSE 8 installed on