soha
soha

Reputation: 115

How to get a folder path dynamically?

I have a Business folder(e:\Business) in this folder I have compiled file .I want use this folder in my main program .My main Program is in the Main folder(e:\ProjectFile\Main) .

I want get the path of Business folder dynamically .I use this statment but didn't work :

String loadedClassPath = System.getProperty("user.dir")+System.getProperty("file.separator")+"Business";

            File operatorFile = new File(loadedClassPath);
            URL operatorFilePath = operatorFile.toURL();          
            URL[] operatorFilePaths = new URL[]{operatorFilePath};
            ClassLoader operatorsClassLoader = new URLClassLoader(operatorFilePaths);
            Class[] operatorClass = new Class[]{ operatorsClassLoader.loadClass("Plus"), operatorsClassLoader.loadClass("Minus"),operatorsClassLoader.loadClass("Multiply") , operatorsClassLoader.loadClass("Divide") }; 

I think this part is not correct :

String loadedClassPath = System.getProperty("user.dir")+System.getProperty("file.separator")+"Business";

Can anyone help me?

Upvotes: 0

Views: 2828

Answers (1)

Andreas
Andreas

Reputation: 159185

Since "e:\Business" is entirely unrelated to

  • the location of your Java code
  • your home directory (user.dir)
  • any other well-know Windows or Java directory

you have to tell the program where/what it is.

Some options are:

  1. Hard-code in Java program. Not good
  2. Pass as argument to main.
  3. Store in a property file that is located in one of the directories mentioned above.

There are likely more options, but option 3 is very common, option 2 is less common but might be better choice depending on circumstances, and option 1 is highly discouraged.


Note: When constructing a path/file name, use new File(parent, child), or better yet, use the newer Paths.get(first, more, ...).
"Newer" refers to Java 7, meaning since July 28, 2011, so not really that new any more.

Upvotes: 2

Related Questions