Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solution when super cannot be first line of constructor in java

Tags:

java

I am using a CSVReader class that takes a local file as input. But now, I need to be able to read local files as well as files having a URL path (like http://example.com/example.txt). To do this, I want to derive a class from CSVReader that identifies whether the file is local or URL, and then pass the InputStream to the parent using super() in the first line of the constructor. What is the elegant way of doing this ?

public class FileReader extends CsvReader{
    public FileReader(){
        if (fileName != null) {

               if (fileName.trim().startsWith("http:")) {
                // it is URL
                URL url = new URL(fileName);
                inputStream = new BufferedReader(new InputStreamReader(
                        url.openStream(), charset),
                        StaticSettings.MAX_FILE_BUFFER_SIZE); 
               }else{
                //it is a local file
                inputStream = new BufferedReader(new InputStreamReader(
                        new FileInputStream(fileName), charset),
                        StaticSettings.MAX_FILE_BUFFER_SIZE);
               } 

            }
            //Now pass the input stream to CsvReader
            super(inputStream, delimiter, charset);  //error - super has to be first line of constructor
    }
}
like image 846
user379151 Avatar asked Mar 12 '12 22:03

user379151


1 Answers

You can write auxiliary methods:

super(createReader(createInputStream(resouce), "UTF-8"), ";");

Your auxiliary method might look like this:

public static InputStream createInputStream(String resource)
{
     resource = resource.trim();

     if (resource.startsWith("http:"))
     {
          return new URL(resource).openStream();
     } else
     {
          return new FileInputStream(new File(resource));
     }
}

public static BufferedReader createReader(InputStream is, String charset)
{
     return new BufferedReader(new InputStreamReader(is, charset));
}
like image 194
Martijn Courteaux Avatar answered Nov 12 '22 11:11

Martijn Courteaux