我的Java程序应该从相对路径加载配置文件。首先,配置文件是从完整路径加载的,并且工作正常。现在我正在尝试从相对路径加载配置文件,所以最后配置文件将从exe文件的相同路径加载。
这是代码。有人能说出我的错误吗?我用评论标记了有问题的一行。
主要课程:
public class App {
private static Object string;
public static void main(String[] args) {
CsvConfiguration conf = CsvConfiguration.getInstance();
}
CsvConfiguration类(相关部分):
public class CsvConfiguration {
private static CsvConfiguration instance = null;
private static Document doc = null;
static{
URI path;
try {
path = Thread.currentThread().getClass().getClassLoader().getResource("/csv-generator/src/main/config/config.xml").toURI(); //my program is collapsing in this line
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(path));
doc.getDocumentElement().normalize();
} catch (URISyntaxException e) {
throw new RuntimeException("Config is unparsable");
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private CsvConfiguration(){
try{
setGenerationRate();
setNumberOfRows();
setNumberOfColumns();
setOutputFolder();
}catch(NumberFormatException nExc){
throw new RuntimeException(nExc);
} catch (IOException e) {
throw new RuntimeException(e);
}
setColumnsList();
}
public synchronized static CsvConfiguration getInstance(){
if (instance==null)
instance = new CsvConfiguration();
return instance;
}
答案 0 :(得分:0)
所以我终于在代码中发现了问题。这比我预想的要容易。
我不得不用以下代码替换有问题的代码行:
File configFile = new File("./src/main/config/config.xml");