0

I need to run a Java File inside a Linux Environemnt .

As part of the code the Java file needs to load a XML File

Please tell me how can i provide the path of the XML File to the java file ?

Can i provide this way ? (Assuming that the java class file and the sample_config.xml are in the same folder ??

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

Please let me know . Thank you very much .

3 Answers3

1

If in the same folder change "/sample_config.xml" to "sample_config.xml", as "/sample_config.xml" would look for the xml file in the root directory (/):

Util.load("sample_config.xml");

EDIT: this would only work if "sample_config.xml" was in the same folder as where the Java process was executing in. See the answer from Qwe.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You can simply use command line arguments. Your java main method has the signature:

public static void main(String[] args)

Anything you pass on the command line gets passed in via the args argument. So if you do

java yourclass sample_config.xml

from the command line, you can then access it like this:

Util.load(args[0]);
Chris
  • 22,923
  • 4
  • 56
  • 50
1

/ means root filesystem folder in *nix, so /sample_config.xml is a file in the root folder.

Just sample_config.xml would be relative to the folder where the program was started from, not relative to the class file location.

The best way to load files from the Java classpath (and your class is in classpath) is via resource loading mechanism. Please follow this link for details: URL to load resources from the classpath in Java

Or, if you can't change the way resources get loaded you need to get the URL of the resource with Class.getResource and pass the path to Util.load.

Something like this should work in your case:

// 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());
Community
  • 1
  • 1
Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95