Two  different ways of closing Input/Ouput streams

OK, the Sun tutorial on Exceptions [http://java.sun.com/docs/books/tutorial/essential/exceptions/putItTogether.html] shows an example where a PrintWriter is closed within a finally block.
Now, the tutorial on bute streams [http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html] shows another example which is different from the first in that the method which contains all the code has throws IOException in the method header, and no catch blocks.
As an experiment, I tried altering the second example by removing the throws IOException from the method header, and adding a catch block within the method. The code is shown below. This code does not compile, due to unreported exception errors on the close statements in the finally block.
My question is, why in the first example can we close a PrintWriter in the finally block without having the method throw IOException, but in the second example we cannot close FileInputStream in a finally block unless we throw the exception in the method header?
ok, here is my modified code from the second example...
import java.io.*;
public class CopyBytes {
     public static void main( String[] args ) {
          FileInputStream inStream = null;
          FileOutputStream outStream = null;
          try {
               inStream = new FileInputStream("xanadu.txt");
               outStream = new FileOutputStream("outfile.txt");
               int c;
               while( (c = inStream.read()) != -1 ) {
                    outStream.write(c);
          catch( IOException e ) {}
          finally {
               if( inStream != null ) inStream.close();
               if( outStream != null ) outStream.close();
}

endasil wrote:
Fguy wrote:
My question is, why in the first example can we close a PrintWriter in the finally block without having the method throw IOException, but in the second example we cannot close FileInputStream in a finally block unless we throw the exception in the method header?
Short answer?  Because FileOutputStream/FileInputStream.close are declared to throw an IOException.  PrintWriter.close() is not.
...Thanks, that helps. I just checked the API docs and of course they confirm what you say, So I can live with that for my current purposes.
I did notice that PrintWriter is like a wrapper for FileWriter, and close() for the FIleWriter class is inherited from OutputStreamWriter, and that close() does throw IOException. So it seems logical that there would be an exception "behind the scenes" which needs to be reported, but I guess this is not the case. Anyways, I have a direction for further investigation. Thanks again.

Similar Messages

  • Two different ways to execute a custom method in an Application Module

    I have a custom method exposed in an Application Module's Client Interface, and i know two different ways of executing it from my ADF Faces project (both works fine):
    1) Calls the method directly through the Data Control:
    MyModule service = (MyModule)JSFUtils.resolveExpression("#{data.MyModuleDataControl.dataProvider}");
    service.myMethod();
    2) Adding a Method Action in the PageDef's file:
    <methodAction id="myMethod" InstanceName="MyModuleDataControl.dataProvider"
    DataControl="MyModuleDataControl" MethodName="myMethod"
    RequiresUpdateModel="true" Action="999"
    IsViewObjectMethod="false"/>
    //Call the method from the binding container
    BindingContainer bindings = getBindings();
    OperationBinding operationBinding = bindings.getOperationBinding("myMethod");
    operationBinding.execute();
    Basically i want to know: what are the differences (pros & cons) of each approach ??

    Hi,
    In my opinion the second way have a advantage, which its method could be invoke automatically using a invokeAction on pageDef, if necessary.
    regards

  • Create bid invit. from template in two different ways has different consequ

    Hi everybody
    "Create bid invit. from template in two different ways has different consequuences"
    When I create a bid invitation from a previous template, from the template search results (Icon_create SAPLBBP_BID_INV 1010) my bid is published but then stay in the model search and the status is wating for approval. But no workflow started in BBP_PD.
    If I use the same template for creating a new bid from the detail using the create bid invitation button, the bid invitation is created correctly.
    I have configured the two events for the BUS2200 object and both of them have an initial condition.
    It seems that the two actions trigger different events or something like that
    Does anybody why it is occurring this and how I could link the workflow without approval for this case.
    Thanks

    Hi
    What SRM version are you using ?
    <b>Please see these SAP OSS notes / links, which might help -></b>
    <u>Note 976752 - Bidding Worklfows are not triggered correctly
    Note 941417 - Creating a bid invitation from template in the background
    Note 971752 - Incorrect approval preview in bid approval
    Note 741372 - Separating template search from bid invitation search
    Note 764028 - New bid invitation items not visible in bid
    Note 996907 No approval preview for bid after note 976752
    Note 765771 Workflow error when creating a purchase order from bid
    Note 790930 No warning message in case of jump from bid</u>
    Regards
    - Atul

  • Different ways of closing a jDialog

    Im having a jdialog named SUBDIALOG' which will be invoked by an anotther jdialog named 'PARENTDIALOG'.
    to close the SUBDIALOG im using the method "dispose()" .
    When i reopen the SUBDIALOG a huge run time exception is thrown , which is at the bottom of this mail .
    I came to know that its a bug in JAVA which occurs while closing a frame .
    So please suggest me the different ways of closing a jDialog .
    In the SUBDIALOG ihave used a jTable which is editable .
    Whenever i invoke the dialog(containing the Jtable) for the first time , everything will go fine .
    After closing the dialog , if we re invoke it, i am unable to edit the Jtable . The following error is being thrown .
    java.lang.NullPointerException
    at sun.awt.windows.WInputMethod.dispatchEvent(WInputMethod.java:253)
    at sun.awt.im.InputContext.dispatchEvent(InputContext.java:238)
    at sun.awt.im.InputMethodContext.dispatchEvent(InputMethodContext.java:180)
    at java.awt.Component.dispatchEventImpl(Component.java:3565)
    at java.awt.Container.dispatchEventImpl(Container.java:1627)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
    at java.awt.LightweightDispatcher.trackMouseEnterExit(Container.java:3323)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3180)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
    at java.awt.Container.dispatchEventImpl(Container.java:1613)
    at java.awt.Window.dispatchEventImpl(Window.java:1606)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    When you use the dispose method on your JDialog, it essentially releases the dialog from memory. So if you try to show the window again, that will throw the exception. I assume that you just want to hide the sub window, and not dispose of it.
    Let's say your dialog's class name is MyCoolDialog. Here's the command to close the window (use this inside a JButton's actionPerformed event):
    MyCoolDialog.this.setVisible(false);
    Also, don't forget to set the JDialog's default close operation sometime during the dialog's initialization:
    MyCoolDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
    If you do want to dispose of the window (and not hide it), then remember to create a new reference to the window, set the default close operation to DISPOSE_ON_CLOSE, use the setVisible example I gave you above for the actionPerformed event, and that should bypass your null pointer exception.
    Miscellaneous edits to this post. I'm had a few ID-10-T exceptions this morning...lol.
    Message was edited by:
    HTPC2Good4U

  • How can I align two different text row in the same table in two different way (one centered and the other one on the left)?

    Hi,
    I want to center two different text row that are in the same table but one on the center and the other one on the left. I put a <span> tag hoping that it has been overwhelmed the table's class properties The .bottomsel's font-family and the .Cig84's font-family and colour work but the text-align don't: they're both on the left.
    These are my source and CSS codes:
    Source:
    <table width="600" border="0">
      <tr>
        <td class="bottomref"><p><span class="bottomsel">| <a href="index.html" target="_self">Main</a> | <a href="about.html" target="_self">About</a> | <a href="clients.html" target="_self">Clients</a> | <a href="contact.html" target="_self">Contact</a> |</span><br />
          <span class="credits">Credits: <span class="Cig84">Cig84</span></span></p></td>
      </tr>
    </table>
    CSS:
    .bottomsel {
      text-align: center;
      font-family: Georgia, "Times New Roman", Times, serif;
    .credits {
      text-align: left;
    .Cig84 {
      color: #F00;
      font-family: "Comic Sans MS", cursive;

    Use paragraph tags with CSS classes.
    CSS:
         .center {text-align:center}
         .left {text-align:left}
    HTML:
    <table width="600" border="0">
      <tr>
        <td class="bottomref">
              <p class="center">This text is center aligned</p>
              <p class="left">This text is left aligned</p>
        </td>
      </tr>
    </table>
    Nancy O.

  • Why close File(Input/Ouput)Streams?

    hi,
    is there any penalty for not closing FileInputStreams and FileOutputStreams?
    thanks,
    asjf

    is there any penalty for not closing FileInputStreams
    and FileOutputStreams?Yes, there is:
    - your JVM process may run out of file handles (especially on UNIX);
    - your JVM process will be locking files against File.delete() (on win32).
    Just because Java has automatic garbage collection for memory-based resources does not mean you can be sloppy about everything else.

  • Two different ways to show a JPopupMenu - the differene

    Hi!
    I am wondering what the difference between these lines are:
    myTable.setComponentPopupMenu(tablePopupMenu);and
    tablePopupMenu.show(myTable, evt.getX(), evt.getY());I have noticed that if I use setComponentPopupMenu(Component c) in a MouseListener for a JTable, I can just select a row once. I´m sure there are solutions for that, but stComponentPopupMenu must be harder to work with than a JPopupMenu.show() method. Am I right?

    Again, have you read the API. This method was added to make it easier. Well, the API says if you set a popup menu to a component, then it will pop up (depending on the bindings).
    If I use the JPopupMenu.show() method in a mouseListener, it will also pop up. I can not see the difference. It is still the same amount of code, just one row.
    I just discovered when I was trying with my NetBeans application (almost generated code) and my own written code, that in my own code I was using a mousePressed method and in the NetBeans application a mouseClicked. The functionality of both the codes are now the same after I have changed to mousePressed in my NetBeans application.

  • Iphone 4s freezing at start up then shuts off and keeps restarting then repeating that process over and over. I have tried to reset the phone two different ways and still this problem occurs after I update it or turn off the phone.

    yes the title says most of what is going on.
    I recently reset my phone, losing all contacts and pictures. It was working fine, then after I updated it, it will not turn on completely.
    It starts up with the apple logo
    -goes to the ios 6 (please slide to open) screen
    -then shuts off
    -and repeats the process unless I shut the phone off manually
    I have tried to hold the lock and the home button down to manually reset the phone
    I have also tried reseting the phone completely previously, and I still have this problem.
    Any ideas?
    Thank you!!

    I really don't have an answer for that one. I guess that while trying to get things working correctly, I would use the most basic monitor I had which in your case would be the Eizon using the Thunderbolt port and adaptor.
    When you boot into Safe Mode the startup is quite slow, but you should get the Apple logo and then the spinning gear below it (release the SHIFT key when it appears.) Then after a little more time you should see a gray progress bar appear below the spinning gear. When that disappears the computer will startup to a login screen.

  • Buffered input/output stream

    How the buffereing is done in buffered input/output streams?
    From the API doc I got to know that they use internal buffer to store bytes before they can be read or written. But i found that File input/output stream also have methods like read(byte[]) or write(byte[]). So what is extra in buffered input/ouput streams? Does the phrase "buffered" suggests that bytes can be read from an array or be written to an array? Am i thinking the right way?

    How the buffereing is done in buffered input/output
    streams?
    From the API doc I got to know that they use internal
    buffer to store bytes before they can be read or
    written. But i found that File input/output stream
    also have methods like read(byte[]) or write(byte[]).Thouse are your buffer, not the streams'.
    So what is extra in buffered input/ouput streams?
    Does the phrase "buffered" suggests that bytes can be
    read from an array or be written to an array? Am i
    thinking the right way?No. It means that the stream either prefetches some data even if it's not requested yet, or that it withholds data that it's supposed to write until it's flushed or gets a larger chunk.

  • 2 different ways to setup IPSec ?

    Hello,
    I am currently trying to setup IPSec tunnel between a pfSense router and a Windows Server 2008R2 (The windows server is located behind a router with NAT enable).
    First of all, I found two different ways to configure IPsec on Windows :
    1) Through Windows Firewall with advanced Security
    2) Through IPSec snap-in into MMC.
    Which one should I use ?
    Well, anyhow I got some troubles to negotiate  phase1. By analyzing packets, it turns out that Windows server always return a NO_PROPOSAL_CHOSEN error code.
    My settings for phase1 (on both sides):
    Authentication  method: PSK
    Negotiation mode: main
    Encryption: 3DES
    Hash: SHA1
    DH Key group : 2 (1024)
    Lifetime: 28800
    (NAT-T Enabled on pfSense)
    Finally, I noticed that it is possible to define peer identifiers on pfSense. Is it possible to do the same on the windows server or does it automatically use the IP addresses as peer identifiers ?
    Any help would be greatly appreciated.
    Best regards,

    Hi bibibubu1,
    The 2008r2 can’t establish an IPsec tunnel behind NAT-T have a known issue, please confirm the following KB meet your environment then install the hotfix. Another possible
    is you have select the matching Encryption schemes.
    You cannot establish an IPsec tunnel to a computer that is running Windows 7 or Windows Server 2008 R2 through a NAT device
    http://support.microsoft.com/kb/2523881
    I’m glad to be of help to you!
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How can I call a function via two different eventListener, is it possible?

    Hi...
    I want to call one function two different way... I write following code, but an error appears..
    Could you help me.. ?
    Thanks...!
    /******************************** LET'S CALL VIA TWO DIFFERENT EVENTLISTENER A FUNCTION ***********************************************/
    var trigger:Timer = new Timer(1000, 10);
    function showAll(evt:TimerEvent, olay:MouseEvent):void{
    /* code blocks */
    increase_btn.addEventListener(MouseEvent.CLICK, showAll);
    trigger.addEventListener(TimerEvent.TIMER, showAll);
    trigger.start();
    Gürkan Şahin
    Code Developer/Coder
    Turkey

    var trigger:Timer = new Timer(1000, 10);
    function showAll(evt:*):void{
    /* code blocks */
    increase_btn.addEventListener(MouseEvent.CLICK, showAll);
    trigger.addEventListener(TimerEvent.TIMER, showAll);
    trigger.start();
    Just change the showAll as shown - * is a wildcard - any object/event will work.
    You can also do like:
    function showAll(evt:* = null):void{
    By putting the = null you can call it with the events or just call it like showAll(); if you need.

  • How to compare two different environments

    Can any please tell me how to compare two environments like DEVL to TEST?
    I know how to compare a project(like DEVL to TEST) but i want to see all the changes in all the objects between two different environments.
    Please help me.
    Thank you.

    That is really a good piece of information.
    Does it really matter where we are comparing from?
    i will explain,let us say we have DEV and TST environment.
    let us say both has same project name and the same number of objects but inside the object they may be different(like number of fields in the same record in both environments).
    Now we want to have a compare report between those environments.
    We can do in two different ways, right?
    (1. source DEV, Target TST)
    (2. source TST, Target DEV)
    will the result get changed in both the cases?
    (except like following)
    (first case souce target)
    ( absent *changed)
    (second case would be like following)
    ( souce target)
    ( *changed  absent)
    (but i gess the number of rows in both the cases does not get changed)
    let me know if you can not understand the question. sorry about the confusing explanation

  • Save different Objects in one file by two different streams

    Hi all,
    I have a issue to read two Objects from one file if I write those in two different streams.
    I open the ObjectOutputStream and save an Object to the file. Then I close this stream and file. Then I open the new ObjectOutputStream and save the second Object in the same file. It works Ok. Then I open the ObjectInputStream and try to read those two objects and get java.io.StreamCorruptedException.
    This exception happes only when app tryes to read the second Object.
    this is the code example:
    //Write part
    for (int i=0;i<2;i++)
    File file = new File("test.swp");
    FileOutputStream fileOut = new FileOutputStream(file,true);
    ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
    JobObject jobObj = new JobObject();
    jobObj.setID(i);
    objOut.writeObject(jobObj);
    objOut.flush();
    objOut.close();
    fileOut.close();
    //Read part
    FileInputStream fileOut = new FileInputStream("test.swp");
    ObjectInputStream objOut = new ObjectInputStream(fileOut);
    for (int i=0;i<2;i++)
    JobObject jobObj = (JobObject)objOut.readObject();
    objOut.close();
    fileOut.close();
    Thank for any help.

    Maybe try closing the ObjectInputStream (and re-creating it as needed) within your for loop?
    - Saish
    "My karma ran over your dogma." - Anon

  • I have two different iCloud accounts. I can't sign into photo stream with my personal account and have tried deleting from my iPhone first, then the MacBook Pro. Still won't let me sign in with the personal account. Please help.

    I have two different iCloud accounts - business and personal. I can't sign into Photo Stream with my personal account because it says my business account is my primary account. They are separate but equal accounts. I have tried deleting the iCloud account from my iPhone, then my MacBook Pro and signing in again on both devices. The iPhone says that my primary account ismy personal account (which is good) but my MacBook Pro still will not sign into that account so I can use Photo Stream.
    Any suggestions? This iCloud stuff is getting annoying.

    you have a ps cs4 license for mac and you have some way of finding your serial number.
    if yes, download an install the installation file.  if you already have the installation file, what is its name and file extension?  (eg, if it's one file, it should be a dmg file.)
    if you need the installation file,
    Downloads available:
    Suites and Programs:  CC 2014 | CC | CS6 | CS5.5 | CS5 | CS4 | CS3
    Acrobat:  XI, X | 9,8 | 9 standard
    Premiere Elements:  13 | 12 | 11, 10 | 9, 8, 7 win | 8 mac | 7 mac
    Photoshop Elements:  13 |12 | 11, 10 | 9,8,7 win | 8 mac | 7 mac
    Lightroom:  5.6| 5 | 4 | 3
    Captivate:  8 | 7 | 6 | 5
    Contribute:  CS5 | CS4, CS3
    Download and installation help for Adobe links
    Download and installation help for Prodesigntools links are listed on most linked pages.  They are critical; especially steps 1, 2 and 3.  If you click a link that does not have those steps listed, open a second window using the Lightroom 3 link to see those 'Important Instructions'.

  • Input in one formfield go to two different fields in a MySQL tablerow?

    Hi, I hope you can help me with this.
    How can I have input in one formfield go to two different fields in a MySQL tablerow without having the visitor to type out his input out twice?
    With the second one I would like to use md5.
    Any help is greatly appreciated.

    How can I have input in one formfield go to two different fields in a
    MySQL tablerow without having the visitor to type out his input out
    twice?
    You would need to write your query with the WHERE clause when you update to say "WHERE user=$userid".  That's the most basic way.  The $userid variable would need to come from either a session or a cookie if the user is logged in and you don't want them to enter the information again.  Or if this is from a previous page, the $userid could just be equal to the $_POST variable after sanitization.
    With the second one I would like to use md5.
    That's even simpler.  Before submitting the form, just do $md5_pass = md5($pass);
    http://us.php.net/manual/en/function.md5.php

Maybe you are looking for