如何在Linux环境中为java文件提供XML路径

时间:2012-02-14 11:05:04

标签: java linux

我需要在Linux Env​​ironemnt中运行Java文件。

作为代码的一部分,Java文件需要加载XML文件

请告诉我如何将XML文件的路径提供给java文件?

我能提供这种方式吗? (假设java类文件和sample_config.xml在同一个文件夹中?

Util.load("/sample_config.xml");

请告诉我。非常感谢你。

3 个答案:

答案 0 :(得分:2)

如果在同一文件夹中将"/sample_config.xml"更改为"sample_config.xml",则"/sample_config.xml"会在根目录(/)中查找xml文件:

Util.load("sample_config.xml");

编辑:这只有在"sample_config.xml"与执行Java进程的文件夹相同的情况下才有效。请参阅Qwe的答案。

答案 1 :(得分:1)

您可以简单地使用命令行参数。您的java main方法具有签名:

public static void main(String[] args)

您在命令行传递的任何内容都会通过args参数传入。所以,如果你这样做

java yourclass sample_config.xml
从命令行

,您可以像这样访问它:

Util.load(args[0]);

答案 2 :(得分:1)

/表示* nix中的根文件系统文件夹,因此/sample_config.xml是根文件夹中的文件。

只需sample_config.xml相对于启动程序的文件夹,而不是相对于类文件位置。

从Java类路径加载文件(以及类在类路径中)的最佳方法是通过资源加载机制。请点击此链接了解详情:URL to load resources from the classpath in Java

或者,如果您无法更改加载资源的方式,则需要使用Class.getResource获取资源的网址,并将路径传递给Util.load

这样的事情应该适合你的情况:

// getResource returns URL relative to this class
URL url = this.getClass().getResource("sample_config.xml");
if(url != null) // if file is not there url will be null
  Util.load(url.getPath());
相关问题