Closing chained I/O streams

When chaining high-level I/O streams with low-level streams, without creating a reference to latter, are they getting closed automatically?
Let me clarify the situation.
That is a sample code from a book:
FileInputStream fis = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
* some code here
dis.close();
bis.close();
fis.close();As for me, I prefer cleaner solution, such as:
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("file.txt")));But in this case, I can't close low level stream FileInputStream and BufferedInputStream, since I don't have any references to them.
Does the call to close() on BufferedInputStream object (bis.close()) automatically closes all lower-level streams?
Which snippet is usually considered a better approach to chaining streams?
Thank you.

AntShay wrote:
OK, and what is the preferred way of wrapping streams in real world?You mean individual variables vs. one longer statement that covers them all? I don't think it matters much, and I see both about equally. Some shops may have a standard that says you're not allowed to chain/nest in one statement, and my personal opinion is that it's better practice to have the individual statements, but I don't always follow it.
Also, does that mean, that manually closing FileInputStream and BufferedInputStream is somewhat unnecessary?If they're wrapped by another stream, then yes, closing them is unnecessary, and may actually be harmful, if you do it in the wrong order.

Similar Messages

  • Closed captioning for rtmp streaming video

    hi, is it possible to do closed captioning in  adobe captivate 5.5 if the video is set to rtmp? any reply would be helpful. thanks!

    What is the subject matter of these FLVs? 
    If it's Captivate screen captures, then you could have added the CC text to each slide if you had left them as FMV slides.
    However, if the video content is of other things, e.g. people talking or some type of action captured with a video camera, then I believe your best solution would be to add the Closed Captioning in whatever tool you used to edit and publish the video. 
    As I mentioned before, Captivate doesn't really provide a mechanism for adding CC text to on screen objects that contain audio in any form.  So for example, you cannot add CC text to an SWF that you've inserted as an animation, even though you can record and add audio to that SWF in Captivate.  Videos are in a similar position, except that they usually don't have their audio added in Captivate.  They mostly come with their audio track built in.  This means the only real way to guarantee good synchronisation of the CC text is to have it embedded in the video as well.

  • DataInputStream.close() is blocking while closing the thread's stream.Why?

    I have a DataInputStream in my thread as
    DataInputStream dis = new DataInputStream(System.in);
    I have written a method for closing that DataInputStream as
    public void closeStream(){
    dis.close();
    But when I call closeStream method from my program as
    t.closeStream();
    it blocks the program execution. I have to press 'Enter' to continue.
    Why is it so?
    Thanx in Advance.

    You're creating the DataInputStream around the standard input. Assuming you haven't reassigned System.in, I'm pretty sure that you can't close it. At least, you shouldn't be able to close the standard input.

  • FIREFOX KEEPS STREAMING VIDEOS AFTER TABS OR FIREFOX ITSELF IS CLOSED-

    Hi...this bug has not been fixed and I guess will never be fixed by Firefox developers as they do not consider this a problem... let me give you an example and prove the opposite...
    ''''''HOW TO CRASH YOUR PC AND SPEND A MONTHLY DOWNLOAD LIMIT IF YOU ARE ON MOBILE BROADBAND EVEN WITHOUT NOTICING HOW DID THIS HAPPENEN? EASILY... JUST START USING FIREFOX!!! OH DON’T FORGET TO PAY YOUR CRAZY INTERNET BILLS FOR THE INFORMATION YOU HAVE DOWNLOADED FROM THE WEB EVEN WITHOUT NOTICING IT :)''''''
    Imagine if you are on mobile broadband...you pay for every megabyte you download or you have monthly limit like 10GB you can download per moth...I guess most of the mobile broadband users know exactly what I’m talking about and think twice before downloading stuff from internet because you can easily spent your monthly download limit in a day...
    All you have to do is open Youtube for example and click on 20-50 video links... don’t worry...you don’t have to watch them all...just clink on video links and close all your tabs with videos started to stream...or just close Firefox…What will happen then…? Firefox will be streaming all videos you have opened and even thought Youtube video tabs or web browser itself will be closed Firefox will keep streaming all the videos you have opened... the only way to stop this is by rebooting your mobile modem or rooter...so in other words to stop that from happening you have to switch ON or OF your mobile device every time you didn’t liked a video or want to watch other video so Firefox will not crash your PC and so you don’t spend your monthly limit in one day...
    Man...this issue has been reported so many times and I ‘’really like’’ when Firefox developers spend their time and effort on such silly things like skins and all sort of silly features but do not consider this issues as an issue and keeps focusing on more important ''things'' … I have reported this issue on Bugzilla years ago but still it hasn’t been fixed…man…I love Firefox and running upstairs every time when I decide I don’t want this video to be streaming so I can switch ON or OFF my mobile broadband modem…

    Try safe mode http://support.mozilla.com/en-US/kb/Safe+Mode

  • Socket Exception when closing Server Socket Streams if Client closes first

    Hi
    I have 2 processes - a Server socket and a client socket. If I close the Client process first, and then try closing down the Streams on the Server process, I get a SocketException with message "Socket is closed" when I try and close the 2nd Stream. It does not matter on the order of the Stream being closed down, the exception is always thrown when I try and close the second stream. The code snippets are below:
    SERVER =======
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class ServerSocketTest {
    public static void main(String args[]) {
    try {
    ServerSocket ss = new ServerSocket(9999);
    Socket s = ss.accept();
    // Get refs to streams...
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    // sleep to let client shutdown first...
    try {
    Thread.sleep(10000);
    } catch (InterruptedException e) {
    System.err.println(e);
    System.err.println("B4 inClose: isBound=" + s.isBound());
    System.err.println("B4 inClose: isClosed=" + s.isClosed());
    System.err.println("B4 inClose: isConnected=" + s.isConnected());
    System.err.println("B4 inClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("B4 inClose: isOutputShutdown=" + s.isOutputShutdown());
    s.getInputStream().close();
    System.err.println("After inClose: isBound=" + s.isBound());
    System.err.println("After inClose: isClosed=" + s.isClosed());
    System.err.println("After inClose: isConnected=" + s.isConnected());
    System.err.println("After inClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("After inClose: isOutputShutdown=" + s.isOutputShutdown());
    s.getOutputStream().close(); // will break here with SocketException!
    System.err.println("After outClose: isBound=" + s.isBound());
    System.err.println("After outClose: isClosed=" + s.isClosed());
    System.err.println("After outClose: isConnected=" + s.isConnected());
    System.err.println("After outClose: isInputShutdown=" + s.isInputShutdown());
    System.err.println("After outClose: isOutputShutdown=" + s.isOutputShutdown());
    s.close();
    } catch (Exception e) {
    System.err.println(e);
    CLIENT ======
    import java.net.Socket;
    public class ClientSocket {
    public static void main(String args[]) {
    try {
    Socket s = new Socket("localhost", 9999);
    try {
    // sleep to leave connection up for a while...
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    System.err.println(e);
    s.close();
    } catch (Exception e) {
    System.err.println(e);
    The debug shows that isClosed() is set to 'true' after the first call to s.getInputStream().close(). The Sun API Socket class getOutputStream() has a call to isClosed() at the start of the method - it then throws the SocketException that I get. Why does the SocketImpl do this before I get a chance to call a.getOutputStream().close()?
    One final thing, the calls to s.isInputShutdown() and s.isOuputShutdown always seem to return false even if the Streams have had their .close() method called.
    Any ideas/help here greatly appreciated.
    Thanks
    Gaz

    Ok, I know what's going on now - I needed something to do on Friday afternoon anyhow!
    Basically if you call either getOutputStream.close() or getInputStream().close(), the underlying Sun implementation will close the Socket.
    Here's what's happening under the covers in the Sun code:
    s.getInputStream() is called on the Socket class.
    The Socket class holds a reference to the SocketImpl class.
    The SocketImpl class is abstract and forces sublclasses to extend it' s getInputStream() method.
    The PlainSocketImpl extends SocketImpl.
    PlainSocketImpl has a getInputStream() method that returns a SocketInputStream. When the stream is created for the first time, the PlainSocketImpl object is passed into the Constructor.
    The SocketInputStream class has a close() method on it. The snippet of code below shows how the socket is closed:
    <pre>
    * Closes the stream.
    private boolean closing = false;
    public void close() throws IOException {
         // Prevent recursion. See BugId 4484411
         if (closing)
         return;
         closing = true;
         if (socket != null) {
         if (!socket.isClosed())
              socket.close();
         } else
         impl.close();
         closing = false;
    </pre>
    So, it seems that out PlainSocketImpl is getting closed for us, hence the SocketException being thrown in Socket.getOutputStream() when I call it after Socket.getInputStream()/
    I've not had a look at the reason why the calls to s.isInputShutdown() and s.isOuputShutdown always seem to return false even if the Streams have had their .close() method called though - any thoughts appreciated.
    Thanks
    G

  • How do I close nested streams?

    Hi,
    I learned that it is very important to close streams. But how do I close a nested stream?
    //Open new zip input stream with a nested file input stream
    zip_input_stream = new ZipInputStream(new FileInputStream(zip_archive));
    //Close zip input stream
    zip_input_stream.close();
    //How do I close the file input stream??

    BalusC wrote:
    da.futt wrote:
    There's something to be said for this. After all, there's no guarantee at all that a wrapping stream will close its delegate, is there?
    Under each [http://java.sun.com/developer/technicalArticles/Streams/ProgIOStreams/index.html] tells:
    Similarly, when closing chained streams, you only need to close the outermost stream class because the close() call is automatically trickled through all the chained classes
    When using legacy classes... sure. But I hope you'll readily admit it would be very easy to write an InputStream that doesn't "trickle through"
    Hey, don't look at me like this! I wouldn't bother either. I'm just trying to comfort filestream's paranoia! :)

  • 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

  • Accessing data at different levels in a chain of InputStream types

    Hi, I have a requirement to see both the pre- and post- filtered/processed InputStream data read through a chain of input streams. I?m assuming this is a fairly common requirement, and I have come up with a solution that works, but wanted to see if anyone had a better idea ? I?m pretty sure I?m violating some InputStream usage conventions or something here.
    Basically, I am using AudioInputStream in AudioSystem to read and decode (so that I can play) an encoded (MP3) audio file. This requires two AudioInputStreams, one to access the encoded source and one to read the decoded audio data:
    AudioInputStream encodedAIS = AudioSystem.getAudioInputStream(url);
    // set up target audio format (standard AudioFormat.Encoding.PCM_SIGNED for playback using a standard SourceDataLine)
    AudioInputStream decodedAIS = AudioSystem.getAudioInputStream(targetAudioFormat, encodedAIS);With this, I can read and then play as follows:
    // set up SourceDataLine
    decodedAIS.read(?); // read
    standardSDL.write(?); // playWhat I?ve done to access the original encoded data is insert a subclass of FilterInputStream in between the encoded and decoded AudioInputStreams. This subclass overrides the read methods to ?retain? a copy of the data most recently read:
    private class FilterToRetainInputStream extends FilterInputStream {
         private class RetainedData {
              private byte[] bytes = null;
              private int offset = -1;
              private int length = -1;
              private RetainedData(byte[] b, int off, int len) {
                   bytes = new byte[b.length];
                   System.arraycopy(b, off, bytes, off, len);
                   offset = off;
                   length = len;
         private RetainedData retainedData;
         private FilterToRetainInputStream(AudioInputStream ais) {
              super((InputStream)ais);
         @Override
         public int read(byte[] b, int off, int len) throws IOException {
              int ret = super.read(b, off, len);
              retainedData = new RetainedData(b,off,len);
              return ret;
    }; I then attach this filter to the original source AudioInputStream and attach a second source AudioInputStream to the filter/retainer:
    // the original (encoded) source AudioInputStream
    AudioInputStream firstEncodedAIS = AudioSystem.getAudioInputStream(url);
    // chain new FilterToRetainInputStream to the source AudioInputStream
    FilterToRetainInputStream retainer = new FilterToRetainInputStream(firstEncodedAIS);
    // chain a second source AudioInputStream to the new FilterToRetainInputStream
    AudioInputStream secondEncodedAIS = new AudioInputStream(retainer,firstEncodedAIS.getFormat(),firstEncodedAIS.getFrameLength());
    // and finally, as before get a playable (decoded) AudioInputStream given a target format and a source (encoded) AudioInputStream
    AudioInputStream decodedAIS = AudioSystem.getAudioInputStream(targetAudioFormat, secondEncodedAIS);Now, I can access the original (encoded) data when reading from the decoded AudioInputStream:
    byte[] abData = new byte[16000];
    int nBytesRead = decodedAIS.read(abData, 0, abData.length);
    FilterToRetainInputStream.RetainedData encodedData = retainer.retainedData;I don?t really like this solution for a couple of reasons - I?m using a filter that doesn?t really ?filter? anything, I need a second AudioInputStream to attach to the filter and I?m passing an audio input stream through a filter (which is not an audio input stream). Any ideas or suggestions would be appreciated or is it okay to do what I?m doing ? thanks.

    For quick assistance post testable script.
    Tree processing examples using recursive CTE:
    http://www.sqlusa.com/bestpractices2005/organizationalchart/
    Kalman Toth Database & OLAP Architect
    Free T-SQL Scripts
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Closed caption not working on programs that claim to be cc per itunes

    I just bought my apple tv the month of April 2013.
    I bought tv and movies from itunes that claim to be closed captioned (House MD and various movies).
    I have enabled the appletv to component to run closed captions in English.
    closed captions works on my TV via cable and via DVD, but I am not getting closed captions with my itunes purchases on my appletv.
    What is wrong with AppleTV?
    This is 2013 and I am not encouraged by the apple support community statements from 2009 & 2010, does Apple have this feature fixed in 2013 or are you waiting for the second coming of Steve?

    I have found that if I play from "my computer/library" closed captioning doesn't work at all.  If I use streaming, it works.  You do have to go into settings to turn it on first of course or press and hold the select button (press and hold only gives you closed caption option when streaming)

  • Getting errors while writing to a BLOB column using PrepareStatement

    Hello,
    I am getting the following errors when I am trying to insert in a BLOB in the oracle 9i database:
    java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1 ORA-06502: PL/SQL: numeric or value error ORA-06512: at line 205 ORA-22297: warning: Open LOBs exist at transaction commit time
    It gets inserted into the BLOB column correctly even after throwing exception.I am using the following code:
    String outputXML = outputXML //Some huge string having a length of 52k
    String pKey = "DATA-WORKATTACH-URL MELLONFINCORP-GSS-CPG E-444!20061130T211932.030 GMT";
    String createDateTime = "20061212T145931.448 GMT";
    String createOpName = "Haque, Nadeem";
    String createOperator = "ADCDTB6";
    String createSystemID = "WFE";
    String insName = "TESt INS";
    String objClass = "Data-WorkAttach-Note";
    String updateDateTime = "20061207T191900.510 GMT";
    String updateOpName = "Haque, Nadeem";
    String updateOperator = "ADCDTB6";
    String updateSystemID = "WFE";
    String label = "This is a test for label";
    String attachDate = "20061207T191900.510 GMT";
    String attachedBy = "Nadeem";
    String attachName = "Nadeem Haque";
    String note = "This is a test note";
    String refObjectKey = "E-438!20061130T211932.030";
    String replicationDate = "20061207T191900.510 GMT";
    try{
    java.sql.PreparedStatement pstmt = null;
    java.sql.Statement stmt = null;
    java.io.OutputStream tempBlobOStream = null;
    oracle.sql.BLOB tempBlob = null;
    javax.naming.Context ctx = new javax.naming.InitialContext();
    tools.findPage("tempWorkPage").putString ("testctx", ctx.toString());     
    javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("jdbc/gswWorkflowReportingData");
    tools.findPage("tempWorkPage").putString ("testds", ds.toString());
    java.sql.Connection conn = ds.getConnection();
    tools.findPage("tempWorkPage").putString ("testconn", conn.toString());
    java.sql.ResultSet lobDetails = null;
         try{
              byte [] ba = outputXML.getBytes();
              String query = "INSERT INTO GSW06U.pc_data_workattach(PZINSKEY,PXCREATEDATETIME,ATTACHDATE,PXUPDATEDATETIME,PXCREATEOPNAME,PXCREATEOPERATOR,PXCREATESYSTEMID,PXINSNAME,PXOBJCLASS,PXUPDATEOPNAME,PXUPDATEOPERATOR,PXUPDATESYSTEMID,PYLABEL,ATTACHEDBY,ATTACHNAME,NOTE,REFOBJECTKEY,ATTACHSTREAM) values(?,to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),to_date(concat(substr(?,1,8),substr(?,10,6)),'YYYYMMDDHH24MISS'),?,?,?,?,?,?,?,?,?,?,?,?,?,EMPTY_BLOB())";
              tools.findPage("tempWorkPage").putString ("query", query);
              pstmt = conn.prepareStatement(query);
              pstmt.setString(1, pKey); // Bind PZINSKEY
              pstmt.setString(2, createDateTime); // Bind PZINSKEY
              pstmt.setString(3, createDateTime);
              pstmt.setString(4, attachDate);
              pstmt.setString(5, attachDate);
              pstmt.setString(6, updateDateTime);
              pstmt.setString(7, updateDateTime);
              pstmt.setString(8, createOpName);
              pstmt.setString(9, createOperator);
              pstmt.setString(10, createSystemID);
              pstmt.setString(11, insName);
              pstmt.setString(12, objClass);
              pstmt.setString(13, updateOpName);
              pstmt.setString(14, updateOperator);
              pstmt.setString(15, updateSystemID);
              pstmt.setString(16, label);
              pstmt.setString(17, attachedBy);
              pstmt.setString(18, attachName);
              pstmt.setString(19, note);
              pstmt.setString(20, refObjectKey);
              pstmt.execute(); // Execute SQL statement
              // Retrieve the row just inserted, and lock it for insertion of the LOB columns
              stmt = conn.createStatement();
              lobDetails = stmt.executeQuery("SELECT AttachStream FROM GSW06U.pc_data_workattach WHERE PZINSKEY = '" + pKey + "' FOR UPDATE");
              tools.findPage("tempWorkPage").putString ("idvalue", pKey);
              // Retrieve Blob streams for AttachStream column and load the sample XML
              if( lobDetails.next()) {
              //Get the CLOB from the resultset
              tempBlob = (oracle.sql.BLOB)lobDetails.getBlob(1);
              tools.findPage("tempWorkPage").putString ("pos1", "at pos1");
              // Open the temporary CLOB in readwrite mode, to enable writing
              tempBlob.open(oracle.sql.BLOB.MODE_READWRITE);
              tools.findPage("tempWorkPage").putString ("pos2", "at pos2");
              // Get the output stream to write
              tempBlobOStream = tempBlob.getBinaryOutputStream();
              tools.findPage("tempWorkPage").putString ("pos3", "at pos3");
              // Write the data into the temporary CLOB from the byte array
              tempBlobOStream.write(ba);
              // Flush and close the stream
              tempBlobOStream.flush();
              conn.commit();
              //Close everything
    tempBlobOStream.close();
              tempBlobOStream = null;
              tempBlob.close();
              tempBlob =null;
              lobDetails.close();
              lobDetails = null;
              stmt.close();
              stmt = null;
              pstmt.close();
              pstmt = null;
              conn.close(); // Return to connection pool
              conn = null; // Make sure we don't close it twice
         catch(java.sql.SQLException sqlexp) {
                   tempBlob.freeTemporary();
                   sqlexp.printStackTrace();
                   tools.findPage("tempWorkPage").putString ("SQLException", sqlexp.toString());
         catch(java.lang.Exception exp) {
                   tempBlob.freeTemporary();
                   tools.findPage("tempWorkPage").putString ("InnerException", exp.toString());
                   exp.printStackTrace();
         finally
              if (lobDetails != null) {
              try { lobDetails.close(); } catch (java.sql.SQLException e) { System.out.println(" Error while Freeing Result sets" + e.toString()); }
              lobDetails = null;
              if (stmt != null) {
              try { stmt.close(); } catch (java.sql.SQLException e) {System.out.println(" Error while Freeing java Statement" + e.toString()); }
              stmt = null;
              if (pstmt != null) {
              try { pstmt.close(); } catch (java.sql.SQLException e) {System.out.println(" Error while Freeing java PrepareStatement" + e.toString()); }
              pstmt = null;
              try{
              if (tempBlob != null) {
         // If the BLOB is open, close it
         if (tempBlob.isOpen()) {
         tempBlob.close();
         // Free the memory used by this BLOB
         tempBlob.freeTemporary();
              tempBlob = null;
              catch (Exception ex) { // Trap errors
              System.out.println(" Error while Freeing LOBs : " + ex.toString());
              if (conn != null) {
              try { conn.close(); } catch (java.sql.SQLException e) { System.out.println(" Error while Freeing Connection" + e.toString()); }
              conn = null;
    catch(java.lang.Exception e)
         tools.findPage("tempWorkPage").putString ("LangException", e.toString());
         e.printStackTrace();
    }

    Hello,
    I am getting the following errors when I am trying to
    insert in a BLOB in the oracle 9i database:
    java.sql.SQLException: ORA-00604: error occurred
    at recursive SQL level 1 ORA-06502: PL/SQL: numeric
    or value error ORA-06512: at line 205 ORA-22297:
    warning: Open LOBs exist at transaction commit
    time
    You're doing exactly what the error says, that is committing with an open LOB. Look at the following piece of code: you write in the LOB, you flush it and then commit. There is no closing of the LOB stream before committing.
    Try putting the tempBlobOStream.close() instruction before the commit.
    // Write the data into the temporary CLOB from the
    he byte array
              tempBlobOStream.write(ba);
              // Flush and close the stream
              tempBlobOStream.flush();
    nn.commit();
              //Close everything
    tempBlobOStream.close();

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • Problem in Download Servlet (Urgent)

    Hai
    i am using an servlet to download files.
    i am facing an problem with that servlet.While downloading, at times it strucks at 290k or 330k.
    Note : Acually i am calling this servlet from a popup window.The popup window closes automatically after one minute irrescpective of the download progress.At times i noticed that the download strucks while the popup closes, whether is causes the problem of strucking.
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Download extends HttpServlet {
    HttpSession session =null;
    File F;
    BufferedInputStream fif;
    ServletOutputStream stream;
    public void init(){
    F=null;
    fif=null;
    stream =null;
    public void doGet(HttpServletRequest request ,HttpServletResponse response) {
    try{
         // Setting Buffer size
    response.setBufferSize(50000);
                   // Setting Content Type
    response.setContentType("application/x-filler");
    int buffersize;
    String cfile="";
    boolean flag=false;
    session = request.getSession(true);
                   //Receiving variables
    String fileName= request.getParameter("filename");
    String filePath = request.getParameter("filepath");
    String downloadFile = filePath + fileName;
    F=new File(downloadFile);
    String download_date = "sysdate";
    String file=F.getName();
    buffersize=(int)F.length();
    byte b[]=new byte[buffersize];
         //Servet output stream to download file
    stream = response.getOutputStream();
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file + "\";");
    int data;
    fif = new BufferedInputStream(new FileInputStream(F));
    //writing data to output stream
    while((data = fif.read()) != -1) {
    stream.write(data);
                   //closing objects
    fif.close();
    stream.close();
    F.delete();
    }catch(java.net.SocketException se){
    System.out.println("SocketException " +se);
    catch(IOException io){
    System.out.println("IOException " + io);
    catch(Exception e){
    System.out.println("Exception " +e);      
    }

    I guess your closing of the window is your problem. Your servlet looks just fine to me.
    Try calling this servlet from a browser and see if it still stops..

  • Applet - Server socket problem

    Hello i'm trying to develop a simple chat application
    The applet connects to the server via a socket and it can successfully send a line of text to the server and receive one back.
    But if I try to put a loop in to receive more lines the applet doesn't start
    here is some source, i'd appreciate any help
    * ChatClient.java
    * Java Applet for communicating with server
    import java.io.*;
    import java.net.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ChatClient extends Applet
         public Panel input;
         public OutputPanel output;
         public PrintWriter out = null;
    public BufferedReader in = null;
         public Socket client = null;
         public Label label;
         public TextField itext;     
         public boolean connected = false;
         public String fromServer = "";
         public void init()
              setLayout( new BorderLayout() );
              input = new Panel();
              input.setLayout( new FlowLayout() );
              label = new Label( "Enter Message" );
              itext = new TextField( 15 );
              TextHandler handler = new TextHandler();
              itext.addActionListener( handler );
              input.add( label );
              input.add( itext );          
              output = new OutputPanel();     
              add( "South", input );
              add( "Center", output );
         public void start()
              String host = getDocumentBase().getHost();          
              try
                   // create socket connection
                   client = new Socket( host, 4444 );
                   out = new PrintWriter( client.getOutputStream(), true );
    in = new BufferedReader( new InputStreamReader( client.getInputStream() ) );
              catch (UnknownHostException e)
                   System.err.println("Don't know about host: 10.1.7.2.");
    System.exit(1);
              catch (IOException e)
    System.err.println("Couldn't get I/O for the connection to: 10.1.7.2.");
    System.exit(1);
              output.otext.append( "Chat client started, listening\n\n" );
              listen();               
         public void listen()
              out.println( "Client 1" );
              try
                   fromServer = in.readLine();
                   output.otext.append( "Server: " + fromServer + "\n\n" );
                   connected = true;
                   //do
                   //     fromServer = in.readLine();
                        System.err.println( "Server: " + fromServer );
                   //     if ( fromServer.equals( "Bye" ) )
                   //          connected = false;
                   //     output.otext.append( "Server: " + fromServer + "\n\n" );
                   //}while ( connected );
              catch( IOException io )
                   System.err.println( "Cannot read from server" );
                   io.printStackTrace();
         public void sendData ( String s )
              out.println( s );
              //output.otext.append( "Client: " + s + "\n\n" );
         public void destroy()
              try
                   out.println( "Bye" );
                   out.close();
                   in.close();
                   client.close();
              catch( IOException io )
                   System.err.println( "Error closing Socket or IO streams");
                   io.printStackTrace();
    class TextHandler implements ActionListener
         public void actionPerformed( ActionEvent e )
              sendData( e.getActionCommand() );
    public String getAppletInfo()
              return "A simple chat program.";
         public static void main(String [] args)
              Frame f = new Frame( "Chat Applet" );
              ChatClient chatclient = new ChatClient();
              chatclient.init();
              chatclient.start();          
              f.add( "Center", chatclient );
              f.setSize( 300, 300 );
              f.show();
    class OutputPanel extends Panel
         public TextArea otext;
         public OutputPanel()
              setBackground( Color.white );
              setLayout( new BorderLayout() );
              otext = new TextArea( 6, 60 );
              otext.setEditable( false );
              add( "Center", otext );
              setVisible( true );
    public void paint(Graphics g)
    }

    I think you have to modify the loop, which receive data from your socket.
    here an example which I tryed
    hope I can help you
    while (z==1)
    anzeige = in.readLine();
    if (anzeige.charAt(0) == ende.charAt(0) && anzeige.charAt(1) == ende.charAt(1) && anzeige.charAt(2) == ende.charAt(2)) // searching for the end"-~-"
    break;
    textField.add(anzeige);

  • Runtime.exec() fails sometime to execute a command

    Hello,
    I have a program thats using Runtime.exec to execute some external programs sequence with some redirection operators.
    For e.g, I have some command as follows;
    1 - C:\bin\IBRSD.exe IBRSD -s
    2 - C:\bin\mcstat -n @punduk444:5000#mc -l c:\ | grep -i running | grep -v grep |wc -l
    3 - ping punduk444 | grep "100%" | wc -l
    ...etc.
    These command in sequence for a single run. The test program makes multiple such runs. So my problem is sometimes the runtime.exec() fails to execute some of the commands above (typically the 2nd one). The waitFor() returns error code (-1). That is if I loop these commands for say 30 runs then in some 1~4 runs the 2nd command fails to execute and return -1 error code.
    Can some one help me out to as why this is happening? Any help is appreciated
    Thanks,
    ~jaideep
    Herer is the code snippet;
    Runtime runtime = Runtime.getRuntime();
    //create process object to handle result
    Process process = null;
    commandToRun = "cmd /c " + command;
    process = runtime.exec( commandToRun );
    CommandOutputReader cmdError = new CommandOutputReader(process.getErrorStream());
    CommandOutputReader cmdOutput = new CommandOutputReader(process.getInputStream());
    cmdError.start();
    cmdOutput.start();
    CheckProcess chkProcess = new CheckProcess(process);
    chkProcess.start();
    int retValue = process.waitFor();
    if(retValue != 0)
    return -1;
    output = cmdOutput.getOutputData();
    cmdError = null;
    cmdOutput = null;
    chkProcess = null;
    /*******************************supporting CommandOutputReader class *********************************/
    public class CommandOutputReader extends Thread
    private transient InputStream inputStream; //to get output of any command
    private transient String output; //output will store command output
    protected boolean isDone;
    public CommandOutputReader()
    super();
    output = "";
    this.inputStream = null;
    public CommandOutputReader(InputStream stream)
    super();
    output = "";
    this.inputStream = stream;
    public void setStream(InputStream stream)
    this.inputStream = stream;
    public String getOutputData()
    return output;
    public void run()
    if(inputStream != null)
    final BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 128);
    String line = null;
    try
    while ( (line = bufferReader.readLine()) != null)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.DEBUG,line);
    //output += line + System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
    output += line + "\r\n";
    System.out.println("<< "+ this.getId() + " >>" + output );
    System.out.println("<< "+ this.getId() + " >>" + "closed the i/p stream...");
    inputStream.close();
    bufferReader.close();
    catch (IOException objIOException)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("io_exeception_reading_cmd_output")+
    objIOException.getMessage());
    output = ResourceString.getString("io_exeception_reading_cmd_output");
    else
    output = "io exeception reading cmd output";
    finally {
    isDone = true;
    public boolean isDone() {
    return isDone;
    /*******************************supporting CommandOutputReader class *********************************/
    /*******************************supporting process controller class *********************************/
    public class CheckProcess extends Thread
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;
    public CheckProcess(Process monitoredProcess)
    super();
    this.monitoredProcess = monitoredProcess;
    continueLoop =true;
    public void setMaxWait(final long max)
    this.maxWait = max;
    public void stopProcess()
    continueLoop=false;
    public void run()
    //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
    final long start1 = System.currentTimeMillis();
    while (true && continueLoop)
    // after maxWait millis, stops monitoredProcess and return
    if (System.currentTimeMillis() - start1 > maxWait)
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    return;
    try
    sleep(1000);
    catch (InterruptedException e)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    System.out.println(ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    else
    System.out.println("Exception in sleep" + e.getLocalizedMessage());
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    /*******************************supporting process controller class *********************************/

    Hi,
    Infact the command passed to the exec() is in the form of a batch file, which contains on of these commands. I can not put all commands in one batch file due to inherent nature of the program.
    But my main concern was that, why would it behave like this. If I run the same command for 30 times 1~3 times the same command can not be executed (returns with error code 1, on wiun2k pro) and rest times it works perfectly fine.
    Do you see any abnormality in the code.
    I ahve used the same sequence of code as in the article suggested by
    "masijade". i.e having threads to monitor the process and other threads to read and empty out the input and error streams so that the buffer does not get full.
    But I see here the problem is not of process getting hanged, I sense this because my waitFor() returns with error code as 1, had the process hanged it would not have returned , am I making sense?
    Regards,
    ~jaideep

  • NullPointerException in the attack method.

    Hi Guys i getting a NullPointerException on the attack() method,i've been trying to figure it out for some hours but i failed.Pls help.
    * Intruder.java
    * Created on March 2, 2007, 7:31 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package org.biyela.security;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.*;
    public class Intruder
        private String host_name = "localhost";
        private static final int PORT = 8000;
        private ObjectInputStream objectReader;
        private ObjectOutputStream objectWriter;
        private Socket socket;
        public Intruder()
        public void connect()
            try
                    socket = new Socket(host_name,PORT);
                    System.out.println("Creating the client socket......");
                    objectReader = new ObjectInputStream(socket.getInputStream());
                    System.out.println("Opening the input channel for object data.....");
                    objectWriter = new ObjectOutputStream(socket.getOutputStream());
                    System.out.println("Opening the output channel for object data.....");
                    //return true;
            catch(Exception ex)
                ex.printStackTrace();
               // return false;
        public void attack()
                Sender s = new Sender();
                s.setIdentity("Alice");
                s.setSenderChallenge("encryptthis");
                try
                    objectWriter.writeObject(s);
                    objectWriter.flush();
                    objectWriter.close();
                    System.out.println("<Intruder Instance>.............");
                    System.out.println("Starting reflection attack......");
                   // ObjectInputStream objectReader = new ObjectInputStream(socket.getInputStream());
                    Sender sender = (Sender)objectReader.readObject();
                    System.out.println("Ecrypted challenge:"+sender.getSenderChallenge());
                    System.out.println("Bob challenge:"+sender.getReceiverChallenge());
                   // sender.setSenderChallenge(sender.getReceiverChallenge());
                    //sender.setReceiverChallenge(null);
                   // objectWriter.writeObject(sender);
                catch(Exception ioex)
                    ioex.printStackTrace();
    //    public Object []  handleServerResponse()
    //            Object [] objects = null;
    //            Object obj = null;
    //            int i = 0;
    //            try
    //                    int length =  objectReader.available();
    //                    objects = new Object[length];
    //                    while((obj = objectReader.readObject()) != null)
    //                            objects[i] = obj;
    //                            i++;
    //            catch(Exception ex)
    //                ex.printStackTrace();
    //            return objects;
        public void disconnect()
            try
                //Checking if the client socket is connected
                if(socket != null)
                    if(objectReader != null && objectWriter != null)
                        objectReader = null;
                        System.out.println("Closing the object input stream.......");
                        objectWriter = null;
                        System.out.println("Closing the object output stream.......");
                    socket = null;
                    System.out.println("Closing the client socket......");
               // return true;
            catch(Exception ex)
                ex.printStackTrace();
               // return false;
    }

    You only have to look at the stack trace to get the line number where the NPE is happening so there's no reason why you can't solve it yourself.
    However there are several other problems with your code:
    (a) You are closing the object output stream in the attack() method, which will disconnect you completely. Closing an input stream or output stream of a socket closes the other stream and the socket. You should just flush the object output stream here.
    (b) You are creating the ObjectInputStream before the ObjectOutputStream. Reverse this, and flush the ObjectOutputStream before you create the ObjectInputStream.
    (c) Your disconnect() method doesn't disconnect. It sets things to null instead of closing something. It should close the object output stream. Because of (a), closing anything else is redundant.
    (d) Your commented-out code based on using available() to determine the size of an array will never work because available() can't do that, and it can't do too much else either. Just read objects in from the stream until you get an EOFException and put them into some form of a List.

Maybe you are looking for