0

I'm developing a tool which will take in an XML file by the user. The tool will perform some manipulation and create a new XML file which then the user can take and do whatever they please with it.

I want to place my jar in a folder (XMLTOOL) alongside user's XML file (input.xml). The hierarchy is as follows:

XMLTOOL
|__tool.jar
|__input.xml

During runtime, I wish to access the file input.xml (or any other XML file the user puts in this folder (e.g. through command line args: java tool newInput.xml)

Currently I'm using:

ClassName.class.getResource(inFile);

Where ClassName is the name of my class. However this only works if input.xml is in the same package as my source files in Eclipse.

So what is the standard convention for structuring resource files in Java projects, keeping in mind that these resources should be accessible when running from a JAR archive.

Sameen
  • 729
  • 6
  • 19
  • I should note that I'm running this on a Windows 7 machine. – Sameen Nov 15 '16 at 13:03
  • 2
    You'll find help here : http://stackoverflow.com/questions/8775303/read-properties-file-outside-jar-file. It will also work fine for XML files – DamCx Nov 15 '16 at 13:04

2 Answers2

1

The simplest way to address files in the local filesystem is through the java.io.File API:

String path=...
File file=new File(path);

// To read the file:
InputStream input=new FileInputStream(file);

// To write to the file:
OutputStream output=new FileOutputStream(file);

path may be absolute or relative to the current directory.

Update

When executing your application from Eclipse, the current working directory is a parameter of your launching: You can set it the arguments tab from the run configuration window. By default, it is the project's directory, but you might set your own custom directory.

Little Santi
  • 8,563
  • 2
  • 18
  • 46
  • Since I'm using Eclipse, the meaning of the phrase "current directory" becomes a bit blurry. Do you mean the folder where my source (src/...) files are located, or where my class files are located (bin/...) ? – Sameen Nov 17 '16 at 16:20
0

You can also create your own namespace say for example (D:\ .. \ Project \ Input \ .xml files) where you can place your xml files and fetch during run-time to avoid confusion.Then,you can use methods like getAbsolutePath() to get the path of xml files and run wherever u want,especially when u run from a JAR file.

You can also use like Maven tool,to manage your projects and directories in a structured and conventional way.

Anands23
  • 758
  • 9
  • 19