我正在使用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),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 } }
解决方法
你可以编写辅助方法:
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)); }