Sign in to follow this  

[java] Java classpath.

This topic is 4478 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have this problem: I am using an engine where a 3d model is being read from a resource path. In order to do that I have to set a classpath to the directory the model resides e.g. C:\file\model, and then add the following string to the reader /obj/box.obj. Of course it works. But, what I want is for the user to select any obj file and be capable of loading. I dont want this to be fixed. I have used JFileChooser where a new window pops up and the user select the file which in turn is stored in "File file = chooser.getSelectedFile();". Since the reader of the engine needs a string I use the method "file.getName();" to take the string name of the file. I also use the method "file.getPath();" to take the string of the path where the file resides. So now what I want is: a way everytime the user selects a file for the path to be added to my classpath thus allowing the reader to read the file. Is there a way to add a classpath in the program itself and not in the IDE properties?

Share this post


Link to post
Share on other sites
Yes, there is. I'm in a hurry right now, but here goes some code:


public static final URLClassLoader createClassLoader() throws Exception {

File dir = new File("directory");
String[] files = dir.list(new JARFilenameFilter()); // custom filter

URL[] urls = new URL[ files.length ];
for (int x = 0; x < files.length; x++) {
File file = new File("directory&#47;" + files[x]);
urls[x] = file.toURL();
}

return new URLClassLoader(urls);
}

Share this post


Link to post
Share on other sites
Not sure if I'm reading this right, but..

The file doesn't *need* to be in your classpath for you to read it. The classpath is just the first place Java will look, if you it ask for a file without an absolute path.

But if you have a File object, that's all you need to get the contents of the file. Just create a FileInputStream or FileReader and start reading. If this engine requires the file as a string, give it the fully qualified name (File.getAbsolutePath), and it should be able to find it.

Share this post


Link to post
Share on other sites

This topic is 4478 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this