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
}
}
You can write auxiliary methods:
Your auxiliary method might look like this: