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:
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With