Solved

BufferedReader returning Stream closed when passed a valid Reader

Posted on 2004-09-13
27
868 Views
Last Modified: 2008-02-01
Hi ,

I have the 2 clasess below. Stock is basically instantiated in class stockPrices, properties are obtained sucessfully from a properties file and then an attemtempt is made to read a flat file of tck prices via the getDataFileFromDir method.

However, as soon as I return from //get the stock File I see the message back from "getting  file ref" and suddenlyI get a java message    -    Stream closed.    Not sure why this is happening.  strTargetfile is just fine. I know that the test if (inString.ready())  may not be necessary,  I don't get far as IN DATA READ.

Please help!

Code snippets (simplified for clarity):

public class stockPrices
{                        
                        Stock datastock = new Stock();
                  
                        //get the properties;                  
                        datastock.getProperties();
                  
                        //get the stock File

                        BufferedReader inString  = datastock.getDataFileFromDir(sDate);      
                        System.Out.println("back from getting  file ref");
                        if (inString.ready()) // data to read
                        {      
                              System.Out.println("IN DATA READ");

                              ...... inString manipulation stuff                        }
                        else
                        {
                              returnCode = 0;      
                              System.out.println("No data for stock file date: " + sDate);                              
                        }

}


public class Stock
{
 
      public BufferedReader getDataFileFromDir(String strDate) throws FileNotFoundException  
      {
             BufferedReader inString = null;
               
             try
             {      // desFolder is obtained from a properties file entry is desFolder= C:\\batch_data\\
                  
                   String strTargetfile=  this.desFolder + strDate +  "_v4.dat";      
                   inString = new BufferedReader(new FileReader(strTargetfile));
                  
             }            
      
            catch (FileNotFoundException e) {
                  System.out.println(" file not found for date: " +strDate);
                        }
            catch (IOException ioe) {
                  
            System.out.println(ioe.getMessage());
                              }
                                
            return  inString;  
      
       }
}
0
Comment
Question by:azsat
  • 8
  • 8
  • 7
  • +2
27 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12048450
>>if (inString.ready()) // data to read

should be replaced by

String line = null;
while ((line = inString.readLine()) != null) // data to read

Are you sure you're not getting exceptions beforehand?
0
 
LVL 92

Expert Comment

by:objects
ID: 12048656
The stream is getting closed, can you post the full code for getDataFileFromDir()
0
 

Author Comment

by:azsat
ID: 12048732
I am indeed doing:
 String line = null;
while ((line = inString.readLine()) != null)

but IN the  if (inString.ready()) // data to read
block.

Here  is the full method getDataFileFromDir()

 public BufferedReader getDataFileFromDir(String strDate) throws FileNotFoundException  
      {
             BufferedReader inString = null;
        
             try
             {      
                   String strTargetfile=  this.desFolder +  strDate +  "_v4.dat";      
                   inString = new BufferedReader(new FileReader(strTargetfile));
                  
             }            
      
            catch (FileNotFoundException e) {
                  
                  System.out.println(" file not found for date: " +strDate);
                  try
                  {
                        inString.close();
                  }
                  catch (IOException ioe) {}       
                  
                    
            }
            catch (IOException ioe) {
                  cat.error(ioe.getMessage());
                  //System.out.println(ioe.getMessage());
                  try
                  {
                        inString.close();
                  }
                  catch (IOException e) {}       
            
            }
                                
            catch (Exception e)
            {       cat.error(e.getMessage());
                   //System.out.println(e.getMessage());
                  try
                  {
                        inString.close();
                  }
                  catch (IOException ie) {}
            }      

            return  inString;  
      
       }
      
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 86

Expert Comment

by:CEHJ
ID: 12048764
You need to check (as i mentioned earlier) that no excpetions are thrown
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12048806
You should probably simply return null if there's a problem and then do not

>>if (inString.ready()) // data to read

but

if (inString != null) // data to read



0
 
LVL 92

Expert Comment

by:objects
ID: 12048827
>   cat.error(ioe.getMessage());

is this error occurring?
0
 
LVL 92

Expert Comment

by:objects
ID: 12048852
>   public BufferedReader getDataFileFromDir(String strDate) throws FileNotFoundException  

instead of checking ready(), it would be safer to have that method return an IOException
ready() could be false for more reasons than it just failing to open.

  public BufferedReader getDataFileFromDir(String strDate) throws IOException

And in the method re-throw the exception if it occurs
0
 

Author Comment

by:azsat
ID: 12048880
Thanks, I guess there could be an exception with new FileReader(strTargetfile)); however,
I'ven been able to verify that strTargetfile is a correct directory path to the file.

Incidentially, this code is running as a java application in Websphere Application Developer.
and the data file is on my C:\ drive.

The same classes run just fine on Linux!!! where I  have simply changed the desFolder to point to a file on Linux and of course ftp'd the properties file as well.

Does this help?
0
 

Author Comment

by:azsat
ID: 12048941
Sorry Objects,

The cat. stuff has been removed from the code (not using log4j stuff at the mo), I give you the wrong commented version, but the System.out messages are all  there.  

ie.
//cat.error(ioe.getMessage());
           System.out.println(ioe.getMessage());

Are you stuspecting that System.out.println(ioe.getMessage()) is giving me Stream closed?
0
 
LVL 92

Expert Comment

by:objects
ID: 12048962
> Are you stuspecting that System.out.println(ioe.getMessage()) is giving me Stream closed?

No, I'm suspecting an error has occurred somwwhere,

Check it is actaully finding the file and opening it correctly.
0
 
LVL 92

Expert Comment

by:objects
ID: 12048973
add some debug after it is opened:

        String strTargetfile=  this.desFolder +  strDate +  "_v4.dat";    
        inString = new BufferedReader(new FileReader(strTargetfile));
        System.out.println("opened successfully "+strTargetfile);


0
 
LVL 92

Expert Comment

by:objects
ID: 12048985
you don't read from the stream at all in getDataFileFromDir() do you?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12048987
>>instead of checking ready(), it would be safer to have that method return an IOException

? The method that gets the Reader should return null if there's a problem as i mentioned earlier
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12049018
Your method can be simplified as follows:

public BufferedReader getDataFileFromDir(String strDate)
{
      try
      {    
            String strTargetfile = this.desFolder +  strDate +  "_v4.dat";    
            return new BufferedReader(new FileReader(strTargetfile));
      }          

      catch (IOException e)
      {
            e.printStackTrace();
            return null;
      }
}      
0
 

Author Comment

by:azsat
ID: 12049026
> The same classes run just fine on Linux!!! where I  have simply changed the desFolder to point to a file on Linux and of course ftp'd the properties file as well.

I expected near enough complete portability,  and was suprised to get the error as the code
goes into if (inString.ready()) // data to read block and I see the data lines read!


However, I won't be able to put in the extra messages to trap the exceptions  right now as I've had to leave work for the day.

I'll provide feedback tommorow around 2:00AM  PDT . In the mean time if something looks obvious   - please say!

NB the file is is just a flat file of string data.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12049092
Don't forget you need forward slashes in paths on Unix ;-)
0
 
LVL 1

Expert Comment

by:Dave_Toland
ID: 12049957
Theres nothing wrong with the code. Run this (create test.txt):

import java.io.*;


public class ExpTest {                    
   
    public static void main(String[] args){
   
          Stock datastock = new Stock();
          
      
          //get the stock File
            try{
            
                BufferedReader inString = datastock.getDataFileFromDir("x");  
                if (inString.ready()) // data to read
                {    
                     System.out.println("IN DATA READ");                  }
                else
                {
                     //returnCode = 0;    
                     System.out.println("No data for stock file date: ");                        
                }
            }catch(Exception e){
                  
                  System.out.println("urrghhh");
            }
      }
}


class Stock
{
 
     public BufferedReader getDataFileFromDir(String strDate) throws FileNotFoundException  
     {
           BufferedReader inString = null;
             
           try
           {     // desFolder is obtained from a properties file entry is desFolder= C:\\batch_data\\
               
                String strTargetfile=  "test.txt";    
                inString = new BufferedReader(new FileReader(strTargetfile));
               
           }          
     
          catch (FileNotFoundException e) {
               System.out.println(" file not found for date: " +strDate);
                    }
          catch (IOException ioe) {
               
          System.out.println(ioe.getMessage());
                         }
                           
          return  inString;  
     
      }
}


Therefore it must be either that the file you're trying to open is empty, in which case it will return that is not 'ready()' or the file doesn't exist in which case you'll get an exception.
0
 
LVL 16

Expert Comment

by:gnoon
ID: 12052149
Hi zasat,

You've specified in code that getDataFileFromDir() function will throws the FileNotFoundException, but inside the function, in the catch block, do closing stream instead and no such exception throwing.

I very quite sure that the command
               try
               {
                    inString.close();
               }
               catch (IOException ioe) {}
cause your stream closed. This mean that an exception occur while openning the file .dat. Maybe it was locked by another application or did not exists on path.
0
 

Author Comment

by:azsat
ID: 12058949
Hi,

Well I've discovered that the problem is with the entry for desFolder in the properties file.

The previous entry was desFolder= C:\\batch_data\\ as mentioned above.

 What I did was a bit of hard coding  and put

new FileReader("C:\\batch_data\\D20040910_v4.dat")

this worked so in the properties file I put  desFolder= C:\\\batch_data\\\  and the code works OK.

Note the three back slashes.   Now this works.  My only question is - is this the right thing to do for reading in a file sitting on my C drive?

 
 
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 100 total points
ID: 12059215
You'll find it easier to do

c:/batch_Data/D20040910_v4.dat
0
 
LVL 92

Assisted Solution

by:objects
objects earned 100 total points
ID: 12060319
>  My only question is - is this the right thing to do for reading in a file sitting on my C drive?

Java looks after platform specific file seperator for you, there is no need to use that. You can use / for all platforms.
0
 

Author Comment

by:azsat
ID: 12069185
Hi

Ok, but I'm still unclear what the entry should be in properties file , I do not want to hard code the file name in te properties file, I just want the path of the location in there.

desFolder=  ?

NB
 desFolder= C:\batch_data\

or  desFolder= C:\\batch_data\\

did not work.

0
 
LVL 92

Expert Comment

by:objects
ID: 12071421
try:

desFolder=C:/batch_data/
0
 
LVL 16

Assisted Solution

by:gnoon
gnoon earned 50 total points
ID: 12071461
>but I'm still unclear what the entry should be in properties file

Depends on how did you get the entry from the properties file.

If you're using java.util.Properties class, the entry should be either

   desFolder=c:\\batch_data\\ or
   desFolder=c:/batch_data/

You'll get a correct path. For more information, please visit here http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream) .

But even if you're getting the entry manually with a file reader, e.g. FileReader, the entry can be

   desFolder=c:\\batch_data\\ or
   desFolder=c:/batch_data/ or
   desFolder=c:\batch_data\
0
 

Author Comment

by:azsat
ID: 12079310
Ok Guys, let me try these options out - hopefully I'll be able to tie this up tommorow.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12089190
8-)
0
 
LVL 1

Expert Comment

by:Dave_Toland
ID: 12091435
like i said, the problem was not with the code, just the file retrieval mechanism.  thanks for the acknowledgment.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
check java version using powershell 13 181
jboss 7.1 start up error 1 41
maven disable workspace resolution 1 23
Problem to Alipay 10 46
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This video teaches viewers about errors in exception handling.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question