Solution when super cannot be the first constructor line in java

I use the CSVReader class, which takes a local file as input. But now I need to be able to read local files, as well as files that have a URL (e.g. http://example.com/example.txt ). To do this, I want to get a class from CSVReader that identifies whether the file is a local or URL, and then pass the InputStream to the parent element using super () in the first line of the constructor. What is an elegant way to do 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 } } 
+6
source share
4 answers

You can write helper methods:

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

Your helper 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)); } 
+11
source

You can declare your constructor as private and create a static factory method that will perform a check before calling the constructor.

+7
source

Move the code to compute the super() arguments for the static function, and call it inside super() .

+2
source

You can reorganize your code to include a static method that will create all the necessary things, and then call the constructor:

 public class FileReader extends CsvReader { public static FileReader createFileReader(String filename, String delimiter, String charset){ if (fileName != null) { BufferedReader inputStream; 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); } return new FileReader(inputStream, delimiter, charset); } return null; } public FileReader(BufferedReader inputStream, String delimiter, String charset){ super(inputStream, delimiter, charset); } } 
0
source

Source: https://habr.com/ru/post/910544/


All Articles