null pointer exception reading properties file - java

I really don't know what else to do. I normally put my properties files in my source folder (I use Netbeans, by the way) and when I read it, everything works fine.
Today, I created a new properties file in the source folder and tried to read it and I kept getting a null pointer exception, connoting the nonexistence of the file in the source folder. Yet, there was another properties file in said source folder and I was able to read that one fine. I deleted both properties files and started afresh, but this time I can't seem to read anything.
My codes are fine:
Properties pp = new Properties();
pp.load(getClass().getResourceAsStream("/errors.properties"));
Then I did the clean and build for my project, and now one of the classes can read the errors.properties file (same code, nothing changed), but I'm also now getting a java.lang.NoClassDefFoundError for my second class when I try running it.
WTH!?

Try this:
Properties pp = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("errors.properties");
pp.load(is);
Btw. this is not a bug in NetBeans.
If you use getClass().getResourceAsStream("errors.properties") your error.properties has to be where you class is.
Note: i used InputStream is only because otherwise the line gets too long. Of course you can put both lines into one.

Related

How do you create a file within a Java artifact?

I am currently working on a Java application in Intellij, and I cannot create a file within my artifact. As an example, I'm using File to create a file within the source, which is MainMenuData.txt.
File mainMenu = new File("MainMenuData.txt");
String absPath = mainMenu.getPath();
mainMenu.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(absPath));
In this, I'm using File to make sure that file exists whenever it isn't.
Instead, I'd like to build within the (Production) artifact. Is that doable?
Anything helps. Thanks.
You could do that.
I assume your artifact is a jar file, which is nothing else than a zip file. You can obtain the location of your jar file in the file system and use the Zip File System to modify it. However I'm not sure, if the jvm might have a problem with that and it might not work on windows, since windows likes to block files, that are in use.
Also this would definitely fail, if your jar file is not stored locally.
A better approach would be to store your data files at the appropriate location in your system.
On Linux(and probably mac): <home>/.local/share/<your application name>/
On Linux(global): /var/lib/<application name>
On Windows(I think, better check it yourself): <appdata>/<your application name>
Your code would look something like this(for Linux):
File home = new File(System.getProperty("HOME");
File configDirectory = new File(home, ".local/share/<application name>");
configDirectory.mkdirs();
File mainMenu = new File(configDirectory, "MainMenuData.txt");
For windows do something similar. If you need both, you should check on which you are currently running.

Passing a .JAR program (ran from terminal) a text file as input

I have created a java program that other testers will use to help with their testing. I will be sending them a zip file with the .jar, a readme.txt, and main.properties.txt file.
The main.properties.txt file is a template for the testers to input their DB access credentials. They will update the main.properties file with their db cred's and then attempt to run the .jar from the terminal or command line. The issue I am running into is this. My program needs this updated main.properties.txt file so it can create the connections to our DB's.
What instructions do I need to give in my readme so my program can successfully find the main.properties.txt? Does the main.properties need to be in the same directory as the .jar? Can the testers just create a file on their desktop or documents folders to put the .jar and main.props?
The other question I have is how do I pass this file to my program once its ran from the terminal? Currently it is really easy, because the main.props is part of my program and I can just do something like
Properties prop = new Properties();
FileInputStream in = new FileInputStream("src/main/resources/main.properties");
prop.load(in);
in.close();
But now main.properties is not part of the project anymore. I don't know how to change the code above so that it can find the text from a directory on the local. The location in which they wish to put their main.properties is out of my control so writing a static path will not work. Please help!
There are many ways, I'll show you two.
You need a File object that points to the main.properties file. Then you create a stream on this object new FileInputStream(File) , as you already did by using a String.
The problem of course is to get a relative path to main.properties.txt which works on all systems, regardless where the jar-File is located.
1. Desktop
In this case the main.properties.txt is located at the users desktop. Here is how you access it:
File desktop = new File(System.getProperty("user.home"), "Desktop");
File target = new File(desktop, "main.properties.txt");
Alernativly, if you plan to distribute configuration and property files that do not require user interaction, you may want to use locations like Temp or Documents (Windows).
2. Relative to the jar
Probably one of your best options. Assume the target is in the same folder than the jar-File (or at least in a fix structure relative to the jar). Here is how you access it (related question: how-to-get-the-path-of-a-running-jar-file):
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
File target = new File(jarDir, "main.properties.txt");

Path not found for a property file in Web application?

My Property file location is WebRoot/WEB-INF/Test/property files/Question.properties
Now I want to load the property file using FileInputStream. So I wrote the below code.
Properties pr = new Properties();
pr.load(new FileInputStream("WebRoot/WEB-INF/Test/property files/Question.properties"));
By the above code I got java.io.FileNotFoundException.I am using myeclipse for my development. Can any one suggest the path to read my properties.
You are opening it relative to the current directory. Do you know what the current directory is? Try creating a:
File f = new File("WebRoot/WEB-INF/Test/property files/Question.properties");
Then printing or debug the absolute path of the File object. This will tell you what file you are actually trying to open (i.e. full path).
However, if you are trying to open a 'resource' bundled with your web app (as suggested by /WEB-INF/ being in the path) this is probably not a good way to do it. One alternative is to build your 'resource' into one of your application's .jar files.
See here, for a related answer:
Refer to a web page inside a jar file
use the method InputStream java.lang.Class.getResourceAsStream(String name) instead, this will work when you run your class within eclipse and outside eclipse. and use the same path as what you have mentioned in your code and append "/" at the front.
Hope this helps !
Do one thing right click on Question.properties file click on the properties get the Location of the file.
Properties pr = new Properties();
pr.load(new FileInputStream("Location of the file"));

Null pointer exception while reading properties file

propsdatabase = new Properties();
InputStream dbin = getClass().getResourceAsStream("/properties/database.properties");
propsdatabase.load(dbin);
I am reading my database connection details via a properties file which is named 'database.properties' in a folder named 'properties'. Jus below the root directory.
The code was perfectly working fine when the jar was exported in Eclipse.
But I used Maven project in IntelliJ to get the jar . It throws NUll pointer exception .
Since the Value of dbin is NULL.(I printed and checked also).
I conclude that the path is not recognised to read the file.
Now The things are fine with IntelliJ .
While doing an export as jar in Eclipse the jar although contains propertioes folder IT is not detected. pl help
The reason that getResourceAsStream is returning null is that the /properties/database.properties file is not in the Maven classpath.
Move your properties folder to under /src/main/resources folder and when Maven creates a jar file, the /properties/database.properties resource will be included, and you'll stop getting the NPE.
Yes, getResourceAsStream is no doubt returning null. I suspect that your jar file doesn't include the file. Try running:
jar tvf yourfile.jar
to check. Next, check the build steps for the jar file. It's hard to say what's wrong without seeing the build file, so please edit your question to include that information if it doesn't leap out at you when you look at the steps.
Does your maven build step include the properties file in the jar? Check the jar-file that is produced. If you don't know how you can always rename it and add a ".zip" at the end and open it.
You may try to read the properties file using the path and a FileInputStream:
Properties properties = new Properties();
FileInputStream input = null;
try {
input = new FileInputStream(new File(CONFIGURATION_FILE));
properties.load(input);
}catch(...){...}

File path is working in NetBeans but not in built JAR file

I have a file holding default information that I use to load the textFields of my application. I looked up how to get this built into my jar file when I build and I was told to put it in the source packages and it would be brought along, so I have done that.
File Structure:
Project
-Source Packages
-src
~Java Classes
-defaultFiles
~Defaults.txt
The code I am trying to use is this:
BufferedReader in;
try {
URL resourceURL = FuelProperties.class.getResource("/defaultFiles/Defaults.txt");
in = new BufferedReader(new FileReader(resourceURL.getPath()));
}
And this works perfectly when I run it through NetBeans but when I build the project and try to run it from the jar file it is not grabbing the file.
I have verified that the default file is being built and exists in the same file structure shown above.
If you can help me out with this I would be extremely grateful as I have no idea what is keeping this from working. Thanks.
You have to lookup in the classpath, not on the disk.
The API to use is :
URL resourceURL : this.getClass().getResource("relative path in the classpath");
Once you have the url you can open a stream, etc.
EDIT : in the main method, you of course need to replace
this.getClass()
by
ClassName.class
I found the answer after searching through a couple dozen questions. It turns out that you can only get a InputStream of the data within a file within your JAR not a File object like I was attempting to do.
(If you want the File object you just have to extract the files from the JAR in your program and then you have access to it.)
So the code that got my problem to work was simply replacing this:
URL resourceURL = FuelProperties.class.getResource("/defaultFiles/Defaults.txt");
in = new BufferedReader(new FileReader(resourceURL.getPath()));
With this:
in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/defaultFiles/Defaults.txt")));
And now it is working both inside NetBeans and in the Built JAR file.

Categories