【发布时间】:2014-10-10 00:38:29
【问题描述】:
我的 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;
}
【问题讨论】:
-
试试
new File(this.getClass().getClassLoader().getResource("/path").getPath()) -
我只需要用有问题的行替换您的代码吗? URI类型可以获取文件类型吗?
标签: java xml path relative-path