解决方案时super不能成为java中的第一行构造函数

时间:2012-03-12 22:00:42

标签: java

我正在使用CSVReader类,它将本地文件作为输入。但现在,我需要能够读取本地文件以及具有URL路径的文件(如http://example.com/example.txt)。为此,我想从CSVReader派生一个类,用于标识文件是本地文件还是URL,然后使用构造函数第一行中的super()将InputStream传递给父文件。这样做的优雅方式是什么?

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
    }
}

4 个答案:

答案 0 :(得分:11)

您可以编写辅助方法:

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

您的辅助方法可能如下所示:

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));
}

答案 1 :(得分:7)

您可以将构造函数声明为private,并创建一个工厂静态方法,该方法将在调用构造函数之前进行检查。

答案 2 :(得分:2)

移动代码以计算super()到静态函数的参数,并在super()内调用它。

答案 3 :(得分:0)

您可以重构代码以包含将创建所有必要内容的静态方法,然后调用构造函数:

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);
    }
}