Super cannot be the first line constructor in Java when solving the problem

I'm using the csvreader class, which takes local files as input But now, I need to be able to read local files and files with URL paths (such as http://example.com/example.txt )To do this, I want to derive a class from csvreader to identify whether the file is a local file or a URL, and then pass the InputStream to the parent file using super () in the first line of the constructor What is the 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),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
    }
}

Solution

You can write auxiliary methods:

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

Your auxiliary methods may be as follows:

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));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>