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.

Similar Messages

  • 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.

  • 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.

  • Re: File Input Streams FileNotFoundException

    Hi,
    I'm having problems with file input streams.
    The program is supposed to read from an external file but when I run it in Sun ONE Studio 4 (update 1), it gives me a FileNotFoundException (The system cannot find the file specified). The file, class.dat, is in the same folder as the .java and .class files.
    Anyway, so I run the program through MS-Prompt commands and there is no problem. It executes fine and gives the right output. Go figure.
    Can anyone shed some light on what is going on? Anyone else with the same problem? Is there something I need to configure in SunStudio? Please help...
    Thanks
    The code is taken directly from Sams Java in 21 days.
    // code
    import java.io.*;
    public class ReadBytes {
    public static void main(String[] arguments) {
    try {
    FileInputStream file = new
    FileInputStream("class.dat");
    boolean eof = false;
    int count = 0;
    while (!eof) {
    int input = file.read();
    System.out.print(input + " ");
    if (input == -1)
    eof = true;
    else
    count++;
    file.close();
    System.out.println("\nBytes read: " + count);
    } catch (IOException e) {
    System.out.println("Error -- " + e.toString());

    FileInputStream file = new FileInputStream("class.dat");Is this the line that is giving you the error message? Always, when trying to open a disk file, give the full path. This is because, FileNotFoundException is thrown only in cases when your file cannot be found by your program. But you say that the file exists.
    Try giving your full path for the file...like:
    FileInputStream file = new FileInputStream("C:/Program Files/class.dat");
    //Ofcourse your path will be different. This is just an example!So try giving the full path and let me know.
    Vijay :-)

  • How to get file input stream from the client machine by JSF Fileupload API?

    Dear Friends,
    How to get the file input stream from the client machine by JSF HtmlFileupload or fileupload API. At present, if i execute the file upload code in the client machine, it is able to get the local path of the file and looking for the file in server machine. So i am getting FileNotFoundException.
    E.g., If a file is located at client machine at following location means "C:\Test\Test.txt",
    uploadClass.getFileuploadComponent().getFilename().toString() returns "C:\Test\Test.txt". But it is looking for that file in server and throwing FileNotFoundException.
    Please post your replies soon.
    Thanks,
    JP

    Depends on which version of JSF you're using. If JSF 1.2, I wouldn't even bother trying to hack this into JSF itself unless you can use something like Seam 2 or richfaces.
    http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/rich_fileUpload.html
    http://docs.jboss.org/seam/2.2.1.CR3/reference/en-US/html/controls.html#d0e29259 (look for s:fileUpload)
    But if I were you, a simple non-jsf form with a servlet works best for taking file uploads.
    As for JSF 2.0, there are other ways of getting it done.
    http://balusc.blogspot.com/2009/12/uploading-files-with-jsf-20-and-servlet.html

  • Now that I'm a paid up supporter Maybe you will fix Firefox and return "Close File" to File on the menu toolbar.

    I just degraded from Firefox 3.6 to 9.0.1 and found that one of the most useful tools is missing. On the Menu toolbar under File, "Close File" has been eliminated. Why? Why do I have to close the site I was looking at and go back to my Firefox home page and start all over? Why was "Close File" eliminated? It was one of the most useful tools in Firefox. I'm hoping I haven't gotten rid of the CD that has 3.6 install on it so I can upgrade to a great version of Firefox.
    Bob -
    ''[Personal information removed by moderator. Please read [[Forum and chat rules and guidelines]], thanks.]''

    Some menu entries in the main menu bar are hidden if you use the mouse and only appear if you use the keyboard to open the menu (Bug 626825).
    You can see the difference if you use Alt+F to open the File menu or other menus like the Edit menu (Alt+E) and Bookmarks menu (Alt+B) and compare that to what you see if you use the mouse to open the menu after you have made the menu bar visible by tapping Alt or by pressing F10.
    Add code to userChrome.css below the default @namespace line.
    *http://kb.mozillazine.org/userChrome.css
    The customization files userChrome.css (interface) and userContent.css (websites) are located in the chrome folder in the user profile folder.
    *http://kb.mozillazine.org/Editing_configuration
    <pre><nowiki>@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); /* only needed once */
    /* Always show menu entries with class="show-only-for-keyboard" */
    #navigator-toolbox menuitem[class="show-only-for-keyboard"]:not([hidden="true"]){ display:-moz-box !important; }
    </nowiki></pre>

  • Passing request of file input type to a jsp

    Hi i m using this script for file uploading the form is.... <html > <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <form action="uploadscript.jsp" name="filesForm" enctype="multipart/form-data" method="post">
    Please specify a file, or a set of files:
    <input type="file" name="userfile_parent" value="userfile_parent" >
    <input type="submit" value="submit" value="Send">
    </form> </body> </html> And i am tring to get the url on uploadscript.jsp by using String parentPath=request.getParameter("userfile_parent"); but i foud that its value is NULL it is not working what should i do to get the userfile_parent on uploadscript.jsp help me!!! Message was edited by: UDAY Message was edited by: UDAY
    avajain      
    Posts: 135
    From: Noida , India
    Registered: 5/10/06
    Read      Re: Passing response but getting NULL
    Posted: Sep 20, 2006 2:43 AM in response to: UDAY in response to: UDAY      
         Click to reply to this thread      Reply
    Use method="GET" in place of method="post" .
    Thanks
    UDAY      
    Posts: 26
    From: JAIPUR
    Registered: 8/14/06
    Read      Re: Passing response but getting NULL
    Posted: Sep 20, 2006 3:18 AM in response to: avajain in response to: avajain      
    Click to edit this message...           Click to reply to this thread      Reply
    now it is giving this error message by e.getMessage()
    [br]the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
    the uploadscript is this....
    http://www.one.esmartstudent.com
    can u please help me.

    Here is sample code which we have used in one of our projects with org.apache.commons.fileupload.*.
    You can find String fullName = (String) formValues.get("FULLNAMES"); at the end that gives name of file.
    <%@ page import="java.util.*"%>
    <%@ page import="java.util.List"%>
    <%@ page import="java.util.Iterator"%>
    <%@ page import="java.io.File"%>
    <%@ page import="java.io.*"%>
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@ page import="org.apache.commons.fileupload.disk.*"%>
    <%@ page import="org.apache.commons.fileupload.servlet.*"%>
    <%!     
         //method to return file extension
         String getFileExt(String xPath){ 
                   //Find extension
                   int dotindex = 0;     //extension character position
                   dotindex = xPath.lastIndexOf('.');
                   if (dotindex == -1){     // no extension      
                        return "";
                   int slashindex = 0;     //seperator character position
                   slashindex = Math.max(xPath.lastIndexOf('/'),xPath.lastIndexOf('\\'));
                   if (slashindex == -1){     // no seperator characters in string 
                        return xPath.substring(dotindex);
                   if (dotindex < slashindex){     //check last "." character is not before last seperator 
                        return "";
                   return xPath.substring(dotindex);
    %>
    <%           
    Map formValues = new HashMap();
    String fileName = "";
    boolean uploaded = false;
         // Check that we have a file upload request
         boolean isMultipart = FileUpload.isMultipartContent(request);
         //Create variables for path, filename and extension
         String newFilePath = CoeResourceBundle.getEmailProperties("FILE_UPLOAD_PATH");//application.getRealPath("/")+"temp";
         String newFileName ="";
         String FileExt = "";      
         //System.out.println(" newFilePath"+newFilePath+"/");
         //out.println(" newFilePath"+newFilePath+"<br>");
         // Create a factory for disk-based file items
         FileItemFactory factory = new DiskFileItemFactory();
         // Create a new file upload handler
         ServletFileUpload upload = new ServletFileUpload(factory);
         // Parse the request
         List /* FileItem */ items = upload.parseRequest(request);
         // System.out.println(" newFilePath"+newFilePath+"/");
         // Process the uploaded items
         Iterator iter = items.iterator();
         //Form fields
         while (iter.hasNext()) { 
         //System.out.println("in iterator");
              FileItem item = (FileItem) iter.next();
              if (item.isFormField()) { 
                   String name = item.getFieldName();
                   String value = item.getString();
                   if (name.equals("newFileName")) { 
                        newFileName = value;
                   //System.out.println("LOADING");
                   formValues.put(name,value);
              else { 
              //System.out.println("in iterator----");
                   String fieldName = item.getFieldName();
                   fileName = item.getName();
                   int index = fileName.lastIndexOf("\\");
              if(index != -1)
                        fileName = fileName.substring(index + 1);
              else
                        fileName = fileName;
                   FileExt = getFileExt(fileName);
                   String contentType = item.getContentType();
                   boolean isInMemory = item.isInMemory();
                   long sizeInBytes = item.getSize();
                   if (fileName.equals("") || sizeInBytes==0){ 
                        out.println("Not a valid file.<br>No upload attempted.<br><br>");
                   } else { 
                   // out.println("ACTUAL fileName= " newFilePath"\\"+fileName+ "<br>");
                        //File uploadedFile = new File(newFilePath+"\\", newFileName+FileExt);
                        File uploadedFile = new File(newFilePath+"/",fileName);
                        File oldFile = new File(CoeResourceBundle.getEmailProperties("FILE_UPLOAD_PATH")+"/"+fileName);
                        File oldFileApproved = new File(CoeResourceBundle.getEmailProperties("APPROVED_FILE_LOCATION")+"/"+fileName);
                        try{ 
                             if (!oldFile.exists()&&!oldFileApproved.exists())
                                  item.write(uploadedFile);
                                  uploaded = true;
                             //out.println(fileName+" was successfully uploaded as "+ newFileName+FileExt +".<br><br>");
                        catch (java.lang.Exception e) { 
                             out.println("Errors prevented the file upload.<br>"+fileName+ " was not uploaded.<br><br>");
         String userid = (String) formValues.get("USERID");
         String fullName = (String) formValues.get("FULLNAMES");
         String email = (String) formValues.get("EMAILID");
         String empno = (String) formValues.get("EMPNO");
         String docType = (String) formValues.get("DOCTYPE");
         String desc = (String) formValues.get("MYTEXT");
         String title = (String) formValues.get("TITLEBOX");
         String module = (String) formValues.get("MODULE");
         String techfunctype = (String) formValues.get("TECHFUNCTYPE");
    %>

  • How do I get itunes to play the local file instead of streaming it?

    I have my iTunes Library on an external FW800 drive.  Recently I didn't realize the drive was not attached and tried to play a song.  iTunes couldn't find the file and started streaming it from iTunes Match.  I've since reattached the drive, but iTunes won't recognize the local file.
    Is there a way to get iTunes to recognize the existing local file or is my only option to redownload the file and delete the old one?

    Hi,
    Close Itunes and then hold option key whilst launching Itunes. Select choose library from pop and select the library on your external drive.
    Jim

  • Close File

    Hi,
    I am getting error in Close file .
    For more clarification i am attaching the word document and sample code
    Attachments:
    Bharath_Query.doc ‏179 KB
    Write_File.vi ‏44 KB

    You get an error because your string array is empty and thus the loop thus runs zero times. This means that the output tunnel for the file reference is not a valid reference and the close fails.
    One possible solution would be to feed the file reference via a shift register. Shift registers output the input unchanged if the loop runs zero times while a plain output tunnel will output the default data for the datatype.
    Also:
    your sequence structure has no purpose.
    Your string array should be a control, not an indicator. Now you longer need the local variable.
    This is all you need:
    Message Edited by altenbach on 12-17-2007 11:10 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    WriteNoError.png ‏8 KB

  • Firefox is not sending file inputs through iframe

    i know this ain't a programming forum, but i'm having problems with firefox while trying to send file inputs through iframes.
    this is my code
    <pre><nowiki><form id="popup_form_archivo" method="post" action="'subir_imagen.php" target="wk_iframe" enctype="multipart/form-data">
    <input name="accion" value="subirImagen" type="hidden" />
    <input name="wkimg" type="file" id="popup_prompt_archivo" />
    </form>
    <iframe name="wk_iframe" id="wk_iframe" src="about:blank"></iframe></nowiki></pre>
    i send the form inputs to the iframe called wk_iframe, i get the data from the hidden input but not the file input..
    I dont know why is this happening?, because it used to work.
    Works good in safarin, Opera, Chrome, But not with Firefox
    I must say i love firefox and that's what i'm here..
    Please help me..

    I notice a single quote in action="'subir_imagen.php". Is that quote necessary?
    *https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
    *https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
    This should still be working as the docs indicate.
    Any errors showing in the Web Console (Firefox/Tools > Web Developer;Ctrl+Shift+K) or Browser Console?
    A good place to ask advice about web development is at the mozillaZine "Web Development/Standards Evangelism" forum.
    *http://forums.mozillazine.org/viewforum.php?f=25
    The helpers at that forum are more knowledgeable about web development issues.<br>
    You need to register at the mozillaZine forum site in order to post at that forum.

  • Why do files from my Nikon D200 camera which are shot at 28MB come into Aperture at only 7MB?

    Why do files from my Nikon D200 camera which are shot at 28MB come into Aperture at only 7MB?
    I had these images in Large Fine JPG format at 28MB but when imorted and started working with them they are only & MB files in Aperture?

    Léonie,
    honestly speaking, I have done most of my image adjustments since 2006 (when I bought the D200) in various image processing applications (e.g. Capture One, Bibble 5 - now turned to AfterShot Pro by Corel, Lightroom at a friend's PC). I also tried Nikon's Capture NX but never liked it. Speaking of images that have been worth while keeping and working with as a RAW file I never saw any difference. As far as I can say with respect to Aperture 3 I come to the the same result as I did with the other software.
    People may say that with the disk space being so cheap now it is not worth while thinking about that. But there is one other aspect that can be of advantage in certain situations: The compressed RAWs are transferred faster to and from the the card than the uncompressed files. Also, the time for decompression in applications seems to be shorter than that saved while reading the smaller files.
    Before I started to use the compression feature (which in fact should be not lossless in the case of D200) I studied some reviews on that, of course.
    Citing one of them one could say
    "I tried to make duplicate shots to compare. I gave up. The mechanical exposure repeatability of my camera and nature itself aren't stable enough to let me make two captures close enough to see any possible difference between compressed and uncompressed raw.
    People do see differences. They are seeing fluctuations in their technique shot-to-shot, not any differences due to the compression."
    by Ken Rockwell
    If you are interested, here is the original article by Ken Rockwell.
    Another very elaborate investigation can be found here.
    Again, a quote from the controversal discussion on that comparison:
    "The ‘lossy’ NEF compression is really a clever use of information theory to save space by eliminating redundant raw levels. The noise which is unavoidably present in light effectively dithers tonal transitions so that the compression is *perceptually lossless*."
    by a poster named emil
    As far as I have read elsewhere, newer cameras as the D300 even have really "lossless" compression algorithms.
    Cheers,
    Michael

  • Why has File-Automate-photomerge disappeared from my MacBook Pro? my MacBook Pro CS4?

    Why has File-Automate-photomerge disappeared from my MacBook Pro in CS4 but is still on my iMac?

    Many thanks for your reply, I found Photomerge.jsx on the iMac, although I couldn't find a Presets/Scripts folder in the Application folder but a search found 4 copies of Photomerge.jsx.
    I made a CD of them and inserted it into the MacBook Pro.  I dropped a copy into my Applications folder but when I opened Photoshop CS4 and tried to use it - it wasn't available.  I then dropped it into Photoshop and it works but when I close everything down and re-open Photoshop it is not there.
    Had to leave the Photomerge.jsx file/folder on the desktop and re drop into photoshop to open to use???
    Please help me further.

  • Swing labels and file input

    Okay, let's see if i can explain this in one go...
    I have a file reader class as below:
    package chineseanimals;
    import java.io.*;
    public class AnimalFileReader {
        public AnimalFileReader (String filename) {
             try{
    FileReader fr = new FileReader(filename);
    BufferedReader br = new BufferedReader(fr);
    String s;
    while((s = br.readLine()) != null) {
    System.out.println(s);
    fr.close();
          catch (Exception e)
            {   System.err.println("File input error");
    }This is called up through:
    AnimalFileReader animalFile = new AnimalFileReader(animal.toString().toLowerCase() + ".txt");
    finalAnimal = animalFile.toString();
      public String getFinalAnimal() {
            return finalAnimal;
        }(Part of the Chineseanimals class .getAnimalFile method)
    Which altogether is ran by this:
    private void getAnimalsActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
        String year = tempYear.getSelectedItem().toString(); //tempYear is obtained through a JComboBox
        Chineseanimals getAnimals = new Chineseanimals(year);/* year is convertee into an animal for use in the animal.toString().toLowerCase() above*/
        getAnimals.getAnimalFile();
        resultsLabel.setText(getAnimals.getFinalAnimal());
    }It prints the file no problem, in the NetBeans output box. However, at the Swing label i get:
    chineseanimals.AnimalFileReader@c1cd1fHopefully that all makes some sort of sense. Ultimately i want to get it so that the resultLabel (which is a swing jLabel) displays the contents of the file read at (animal.toString().toLowerCase() + ".txt").
    Where am i going wrong?

    I'm going to assume your questions were rhetorical (mainly because i can't be bothered to answer them) and designed to point me in the right direction as well as make me think i was able to find my own answer.
    Which i did, (completely by myself, that is).

  • Validate: File Input

    Hi Chaps,
    Is there any way of validating a file input field (max file size, banned extentions, etc.) with Spry?
    Cheers

    Don't know why SPRY can't handle file validation, fingers crossed for CS5.
    Cheers for the info, I'll check it out.
    Bo!

  • Object input/output stream

    Hi, i'm currently doing a software enginnering project at university. I need to understand how to save and read from files.
    I've been told to look at object input/output stream, which I have, but I can't get my head around what's written in the books. Does anyone know where i can find a good tutorial on this subject?
    thanks
    AK

    I like the tutorial on this site because it tells you what to use for what you're doing (click on Using the Streams). Hope it helps!
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

Maybe you are looking for

  • Fan shuts off when iBook is moved

    Greetings everyone! I've become bored with helping everyone else out around here I'm hoping someone out there has an answer/some references for me. Here's what's going on: my iBook's fan works just fine--kicks in when it's supposed to, doesn't run ex

  • Wrong Work center picking up Time sheet

    Hi Scenario is as follows: Earlier Employee has HR assignment to one Work center 1 -WC1 Later, Employee was Assigned to Work center 2- WC2 Problem: When booking time sheet in CAT2 ,  for service order, WC1 was picking up, even though in Service order

  • Title to final cut pro

    how can i make my motion titles for my final cut pro project not jiggle? if i create titles in final cut pro, they also jiggle. thanks, dominic

  • Query on DTP error

    Hi BW Experts, I am loading data to master data infoobject from ECC 6.0.The data has come to psa correctly.While running the DTP to move the data from PSA to MASTER DATA INFOOBJECT(ZZEMPLOYEE) some records are showing error. The error is Data record

  • Need to format my system

    Hi, I'm trying to format my computer, but I keep getting a message saying that it was not able to do it. How do I delete everything I've saved?