【问题标题】:Unable to load XML configuration file from relative path无法从相对路径加载 XML 配置文件
【发布时间】: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


【解决方案1】:

所以我终于在代码中发现了问题。这比我预期的要容易。

我不得不用以下代码替换有问题的代码行:

File configFile = new File("./src/main/config/config.xml");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多