Java Properties File not loading - java

I need a configuration file in my program to store some information, I saw some examples of properties files and was trying to use them but whenever I try this second line on NetBeans i get 'Package sortConfig doesn't exist' '<identifier> Expected' and 'Illegal start of type'.
The problem is I already saw some 10 examples all doing this in the same way, and I have no clue to what's going on.
Properties sortConfig = new Properties();
sortConfig.load(this.getClass().getClassLoader().getResourceAsStream("sortConfig.properties"));
Any help would be appreciated
my .java classes and my properties file are on the src, inside the same package folder

It looks like you do not have the fully qualified path to your properties file. You can get to it in 2 ways:-
Using java.util.ResourceBundle:
ResourceBundle bundle
=ResourceBundle.getBundle("br.com.example.sortConfig");
//.properties is implied
or
Using ClassLoader.getResouceAsStream:
sortConfig.load(this.getClass().getClassLoader().getResourceAsStream("br/com/example/sortConfig.propertie"));
For a good tutorial on how to load properties files resources check out this link.

An alternative could be to use this.getClass().getResourceAsStream() which accepts relative pathnames (relative to the package your class is in, that is), so you could simply write
sortConfig.load(this.getClass().getResourceAsStream("sortConfig.properties"));
This is useful when you specifically want to rely on your class and properties file being in the same package. (So when you move one during a refactoring, you'll have to move the other too.)

Related

GWT resourcebundle can't find classpath

So I have a GWT project and on the server side I am trying to load a properties file into a resource bundle, but am failing. I keep getting a missing resource exception because it can't locate the file but every option I've tried doesn't work. I've tried placing the config.properties file in war/config/config.properties as well as src/config/config.properties (so 2 copies) and I've tried calling it the following ways
TestGWTProject.war.config.config.properties
TestGWTProject.war.config.config
TestGWTProject.src.config.config.properties
TestGWTProject.war.config.config
src.config.config.properties
src.config.config
and my current call is this
ResourceBundle bundle = ResourceBundle.getBundle("config");
yet nothing works. Ideally, I'd like to keep it in the war file, but if it has to stay in src no biggie, but I'd like to just be able to find it at this point. What am i overlooking?
If you put your properties in the src folder (as I think you should) you need to give ResourceBundle a class-like qualified name, so that when application gets compiled, it can find the properties file in the classes folder.
In my case, for ex., I place them in my source folder, inside a package. Like this:
src/package/subpackage/subsubpackage/propertiesFile.properties
When I want to load the properties, I use this as the qualified name:
package.subpackage.subsubpackage.propertiesFile
This is the same way you would give your application a full qualified name for a class. The key here is that the properties file is getting copied to the classes folder inside the WAR. So your mistake was telling the ResourceBundle to look into the src folder.

Opening input file using java code in JSP

I am using JSP on NetBeans.
In the java code, I am trying to read data from a file. First I open the file by specifying its path.
Because my code runs on a server (GlassFish), I would like to have my file path independent of the machine where it runs. Therefore, I want to start the path with the folder name that contains the file which is saved on the root of the project directory. I tried so hard to achieve that but I couldn't.
I read online and I found this way, but it still doesn't work:
<%
//building the tree here.
GraphBuilder tree = new GraphBuilder("${pageContext.request.contextPath}\\src\\java\\Database\\OptimizedFullTermFile.pad");
%>
Can anyone help? Thank you.
Just read it from the classpath. Given that you're using the typical src folder representing the Java source code (the Java package/class structure), I assume that the file OptimizedFullTermFile.pad is placed in the Java package java.Database (eek, a capital in package name? lowercase it all). In that case, it's already in the classpath and thus you can just get it straight from there as follows:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("java/Database/OptimizedFullTermFile.pad");
// ...
As to your failed attempt: the EL ${pageContext.request.contextPath} isn't ever going to work in a scriptlet. Even if it did, it's not the right thing, it returns the context path in the webapp URL which is absolutely not part of the local disk file system path, let alone the classpath. Using scriptlets is strongly discouraged since a decade, by the way.
See also:
getResourceAsStream() vs FileInputStream
Where to place and how to read configuration resource files in servlet based application?
You can try the following code to get your directory file in project from the following code.
this.getServletContext().getRealPath("")+[your file path in project web directory]

Does Java getResource method only work with particular extensions?

The following piece of code works fine
getClass().getResource("/index.xml");
However when I do a full refactor to
getClass().getResource("/index.html");
The above line throws NullPointerException. I know I have refactored correctly because I rename the file using IDE smart refactor i.e. the file index.html definitely exists in the same directory. As soon as I switch back to
getClass().getResource("/index.xml");
Everything is fine again. Is there any reason why only the .xml extension works?
As #a_horse_with_no_name mentions, using getResourceAsStream( ) should work fine with any file and any extension.
I'd be inclined to believe (based on the information presented) that your IDE hasn't properly refreshed its file hierarchy after the refactor. I'd suggest running a full clean and build of your project, see if that helps the situation.
So, most of the other answers, the class/class loader shouldn't be looking at file extension You could write a ClassLoader which did that, but it would be odd.
I'm going to take a stab at what your problem is. I am guessing using some IDE (you don't specify which) that is copying certain files from your source folder into the destination (either a jar or a directory of classes and resources). For Java code, you want the compiled .class object files there and not the .java sources. So the IDE will be configured, with some reasonable default [magic], to copy files with only certain extensions. HTML files were used for old package JavaDocs (package-info.html rather than package-info.java which can include package-wide annotations), so are arguably reasonable to exclude by default.
Therefore, you should investigate what the project is doing in this area, and change any configurations accordingly.
Using getResourceAsStream() should work with any file extension (at least it does for me)
Recognised Java Resources are either a class extending ResourceBundle or .property file.
You can write your own extenstions to enable Resource to be gathered from other extensions.
I'm unsure why .xml files are a viable extension. Are you using Java 7?
From the JavaDoc guide:
The name of a resource is independent of the Java implementation; in
particular, the path separator is always a slash (/). However, the
Java implementation controls the details of how the contents of the
resource are mapped into a file, database, or other object containing
the actual resource.
A resource is identified by a string consisting of a sequence of
substrings, delimited by slashes (/), followed by a resource name.
Each substring must be a valid Java identifier. The resource name is
of the form shortName or shortName.extension. Both shortName and
extension must be Java identifiers.
And read this doc which tell us : an absolute resource name is constructed from the given resource name using this algorithm.
getResource() will work regardless of the type of resource. All it does it return a URL. This example works fine for me.
public class Example {
public static void main(String... args) {
System.out.println(Example.class.getResource("jaxb.properties"));
System.out.println(Example.class.getResource("test.xml"));
System.out.println(Example.class.getResource("foo.html"));
System.out.println(Example.class.getResource("danger.exe"));
}
}

Creating a standalone package in java and take some settings from the configuration file

Anyone plz let us know what to do when we have some configuration file which is basically xml.I want to for example give the path to save the image(for my java program) in a folder from some config file (xml in my case).In that case where should the config file be kept.Rt now every thing is converted to jar file when i create a java standalone package.But i want to give some setting from xml file.What to do in that case.How is it possible.This article only provides to create a single jar file for java project but talks nothing about the configuration settings that u can provide from some external source.
Regards
Sagar
I'm not sure I fully understand your question, but if it is where to put the XML file with configuration information, you can place your xml file in the same directory as your jar file, and then pass the XML file name and path into the Jar on the command line when calling the Jar. If you're running it in Windows, this is often done using a shortcut. Then you can get the full path string for the Jar from the main method's String[] arg array that accepts the command parameters.
Sagar,
The fact your java program is a standalone package (.jar file) has no bearing on where your configuration file is stored. Your java package is a program and that program can read any file from the file system that it so desires; it does not have to be part of the code inside the IDE i.e. you don't have to write it when you write the program. What you do need is some way, when you start the program, to find and read said configuration file.
Depending on how you expect the program to be configured, you might put that file in a number of locations. For example, /etc/yourimageprogram/config.xml or c:\program files\yourimageprogram\config.xml or perhaps c:\users\Sagar\Application Settings\yourimageprogram\config.xml. Which you choose of those options really depends on what the use case is and that I can't help with.
However, there are some main points to reading any file:
Does it exist?
Are we allowed to open it for reading?
Are we allowed to open it for writing? Might want to know if we want to update the config?
In Java, typically, you would test this with:
File configfile = new File("C:\test.xml");
if ( configfile.exists() && configfile.canRead() )
{
// read the file
}
else
{
// decide what to do if no config exists.
// might be first run of app.
}
The next stage is to parse the file. There are a number of parsers available for XML including sax and org.w3c.dom. What you need to do is to use these to extract the information you require and store that in a class. Probably a singleton class as you're unlikely to have multiple configuration instances per instance of the program.
I suggest you read about XML Parsers and File Handling under Java. Also look at the File object. See all your options for file io in java. These should give you some indication of how to proceed.

Simulate app.config for Java?

I know that you can use java.util.Properties to read Java properties files.
See: Java equivalent to app.config?
Is there a standard place to put this file? In .NET we put application.exe.config in the same directory as application.exe. The application looks for it here by default.
Java can be made to look for a properties file in the class path but I am struggling to understand the filename/path structure to use and how to use either a standard .properties format or XML format file.
Assuming I have an API packaged in org_example_api.jar (the root package is org.example.api). I don't want to put the properties file inside the jar as it should be editable by the user. I want the user to be able to put the required configuration properties in either a .properties or .xml file somewhere relative to the classpath so I can find it without needing to know anything about the ir file system structure.
Will this work on all systems:
/classpath/org_example_api.jar
/classpath/org/example/api/config.properties OR
/classpath/org/example/api/config.xml
Code:
java.util.Properties = ? //NEED SOME HELP HERE
This purely depends on the type of application you are developing.
1) If it is a web application the best place is inside the WEB-INF/classes/ folder.
2) If you are developing a standalone application there are many approaches. From your example I think the following structure will work.
/<dist>/org_example_api.jar
/<dist>/config.xml
/<dist>/run.sh
In the run.sh you can start the java application providing the current directory also in the classpath. Something like this.
java -cp .:org_example_api.jar ClassToExecute
3) If it is an API distribution it is up to the end user. You can tell the user that they can provide the config.xml in the classpath which should follow some predefined structure. You can look at Log4J as an example in this case.
The world is wide open to you here. The only best practice is what works best for you:
Whatever program the user is running can require the path to the properties file as an argument
Your application can be configured to look in the current directory for config.properties.
If the file can't be found, you could maybe fall back to the user.home directory, or fall back to wherever your application is installed.
Personally I usually have my applications attempt to read properties files from the classpath - but I'm not in a world where I have end-users update/change the file.
Whatever option you choose, just make sure you clearly document it for your users so they know which file to edit and where it needs to be!
You can put the properties file in a directory or JAR in your CLASSPATH, and then use
InputStream is = getClass().getResourceAsStream("/path/goes/here");
Properties props = new Properties();
props.load(is);
(I noticed you mentioned this in your OP, but others may find the code useful.)

Categories