jagdpanzer
jagdpanzer

Reputation: 713

Reading dynamic file paths in java

In my java code, I read/write to files. When I write to a file, I can locate it like this:

FileOutputStream out = new FileOutputStream(new File("../MyProject/MyFile.xls"));

So how come I can't load property files the same way? For example:

config = new FileInputStream("../src/ConfigFiles/config.txt");

The above code does not locate the file. It used to be hardcoded, but I can't continue doing that.

I need to read/write them dynamically as I'll be switching computers and work spaces often. Is there anything special I need to do to read these files?

Upvotes: 0

Views: 3312

Answers (1)

Jose Martinez
Jose Martinez

Reputation: 11992

Property files need to be treated as resources. Resources end up in your classpath and need to be read using the ClassLoader. They get packaged into your JAR/WAR.

getClass().getClassLoader().getResourceAsStream("ConfigFiles/config.txt");

EDIT: To answer your question as to why it worked before but now does not. When you access a file on disk you need to of course have the path to it. The path could be relative or absolute. If you run your code from the same place via your IDE then you should be able to reach files in your project. Specifically files in your src. But your application will not always be executed from the same place (same working directory). As such you need to package some important file with your code (in the JAR or WAR) or you can access the files using absolute path, if you know the file is somewhere on that system.

For example if I need to access a file in /tmp/myFile.txt, and I know that when ever my program executes that file will be there, then I can access it using the FileInputStream you are using and I would pass it the absolute path. But if my program will run on various systems, Linux or windows, and I know the files it needs will not be present on disk, then I can package those files in my JAR/WAR. These files are typically called "resources" or "resource files". For those you use the ClassLoader, as mentioned.

From looking at your code, it looks like that file is in you src directory, hence it will get packaged with your src code into the JAR, and hence is a resource file.

I hope that helps a little.

Upvotes: 2

Related Questions