Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a file to the class path [closed]

How can I save / load a file that is located where my classes are? I don't the physical path to that location before and I want dynamically to find that file.

I want to load an XML file and write and read to it and I am not sure how to address it.

like image 698
Doron Sinai Avatar asked Jan 17 '11 15:01

Doron Sinai


People also ask

How do I put all JARs in a folder classpath?

In general, to include all of the JARs in a given directory, you can use the wildcard * (not *. jar ). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.

Where do I find classpath?

To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.


3 Answers

Use ClassLoader#getResource() or getResourceAsStream() to obtain them as URL or InputStream from the classpath.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/file.ext");
// ...

Or if it is in the same package as the current class, you can also obtain it as follows:

InputStream input = getClass().getResourceAsStream("file.ext");
// ...

Saving is a story apart. This won't work if the file is located in a JAR file. If you can ensure that the file is expanded and is writable, then convert the URL from getResource() to File.

URL url = classLoader.getResource("com/example/file.ext");
File file = new File(url.toURI().getPath());
// ...

You can then construct a FileOutputStream with it.

Related questions:

  • getResourceAsStream() versus FileInputStream
like image 198
BalusC Avatar answered Oct 06 '22 00:10

BalusC


You can try the following provided your class is loaded from a filesystem.

String basePathOfClass = getClass()
   .getProtectionDomain().getCodeSource().getLocation().getFile();

To get a file in that path you can use

File file = new File(basePathOfClass, "filename.ext");
like image 39
Peter Lawrey Avatar answered Oct 06 '22 00:10

Peter Lawrey


new File(".").getAbsolutePath() + "relative/path/to/your/files";

like image 34
user489041 Avatar answered Oct 05 '22 23:10

user489041