Reading from file in Eclipse plugin - java

I need to read the configuration details from a properties file in eclipse. I have put the config.properties at the same level as plugin.xml and in the class file I call:
Properties properties = new Properties();
FileInputStream file;
String path = "./config.properties";
file = new FileInputStream(path);
properties.load(file);
I get a file not found exception. Is there a better way of doing this?

Did you remember to include it in the build?
Secondly, using the classloader resource is probably better anyway
InputStream fileStream = myClass.getResourceAsStream( "/config.properties" );
Also, there is another way of opening a resource URL in eclipse using
url = new URL("platform:/plugin/com.example.plugin/config.properties");
InputStream inputStream = url.openConnection().getInputStream();

Put the properties file in the root of your project. This should be where the user.dir system property is pointing. The FileInputStream constructor looks in this directory for the file.
You can confirm it is in the correct directory by outputting the System Property.
System.getProperty("user.dir");

If it is a plugin, you should tell it that your file must be included into the target. It is set in the build.properties file. Open it and look - you haven't your file mentioned there.
Open plugin.xml, go to build tab and include your file in the binary.build by checking it. Save. That will change the build.properties file correctly. Go to build.properties tab and look at the file again - now you see your file included correctly.
Of course, you could do it by hand, but plugin UI is convenient and you can be sure you haven't any problem ends of line or spaces.
For absolute addressing the files in the plugins look here

Related

ClassLoader.getResource returning null while using File.getAbsolutePath

I have a config.ini file I need to open that is quite far back in directory so I used File.getAbsolutePath() to set the base directory and concatenated the remainder of the path.
Printing the path, I get the correct path that I can paste into file explorer, but the object returned is null.
So I started by initializing my Properties and ClassLoader as such:
Properties prop = new Properties();
ClassLoader classLoader = Test.class.getClassLoader();
Then I create the path. I tried escaping a back slash(1) as well as forward slash(2), both return null but both paths work in file explorer.
String absPath = new File("").getAbsolutePath();
absPath = absPath.concat("\\resources\\config\\config.ini"); // (1)
absPath = absPath.concat("/resources/config/config.ini"); // (2)
then I try to set the URL to open an InputStream
URL res = Objects.requireNonNull(classLoader.getResource(absPath), "Unable to open config.ini");
InputStream is = new FileInputStream(res.getFile());
However, the following returns null.
classLoader.getResource(absPath)
I expected this to properly open the file because the path was correct. I am using Intelij and I read that I needed to add the .ini resource file under settings > compiler, which I did but that did not resolve my issue.
Thank you!
That's not the way to load resources via class-loaders.
If your classpath is something like the following ...
java -cp resources;lib/my.jar ... org.mypack.MyClass
then you load it with this path
getClassLoader().getResource("/config/config.ini");
Your classpath includes the resources folder, and the class-loader loads from there.
The absolute path of the OS is quite certainly not in classpath.
In any case, you must be certain that the resource folder is in classpath.
If your config file is not in classpath then you can't use classloaders to load that file.
Just one more thing, if your configuration is not in classpath, but in a child directory of your working dir, why can't you simply use new FileInputStream("resources/config/config.ini");

How to maintain a configuration file in java application project like a configuration file in C# application?

In C#,when I want to create a configuration file, it's so easy,just right click the mouse and add a new configuration file, this file will be added into the solution and it's so easy to maintain.
But in java, I don't know what method is standard. I see some people use the properites file.If this is the most popular method, can some one tell me where to place this file? I saw some guy put it in the src folder, others put it in an external folder.
Can you tell me which is the standard? And what is the best practice to maintain a configuration.
I don't know if this is the "standard" way but I think it's the easiest. If you place your properties file in your project's root folder
- project
- config.properties
- src
- main
- ...
- test
When you create a File instance in Java and specify a relative filename, then the name is resolved against the directory that Java was launched from
e.g. if you launch java in your command prompt as follows:
cd C:\Users\Tom\example-project
java example-project
and this is your code:
File file = new File("tom.txt");
then the file variable will be resolved to the abolsute path: C:\Users\Tom\example-project\tom.txt
When you Run a project through Eclipse, Eclipse launches java from the root directory of the project, meaning that if you put your config file in the project's root folder then
File file = new File("name-of-config-file.properties");
will resolve to the correct config file on your system.
This has an added benefit if you create a runnable JAR, as you can just place your config file in the same directory as your JAR and the code will continue to work (the config file location will be resolved relative to the JAR).
If you put your config file in /src folder then you need to have separate code for when running from Eclipse and when running as a JAR
With regards to sample code:
//Read properties from disk
File propertiesFile = new File("config.properties");
FileReader reader = new FileReader(propertiesFile);
Properties props = new Properties();
props.load(reader);
//Set and get properties
props.setProperty("NewProperty", "value");
String propValue = props.getProperty("propToGet");
//Write properties to disk
FileWriter writer = new FileWriter(propertiesFile);
props.store(writer, "Added x properties");
Configuration files are used to store,read write user settings.
I think for web apps you can use web.xml.And for other you should use Properties class to read and write settings.
As for where to place it,If you dont specify path it is stored in your root folder other than that you have to provide explicit path.

File path errors in eclipse? (Java Spring)

InputStream inp = new FileInputStream("src/main/resources/ExportHour.xls");
I have a file in the src/main/resources folder of my Java Spring project.
I am attempting to create an inputstream in one of my Controllers, however I always get a file not found exception. When I change the path location to point specifically to the file on my machine, it works fine.
Any way I can make it so the file can be found within the java project?
Try with spring ClassPathResource.
InputStream inp = new ClassPathResource("ExportHour.xls").getInputStream();
That is because the resources folder in maven is put in your jar file directly i.e. the ExportHours.xls file is put inside your jar in the root directory.
It sounds like you could just change the working directory of your process - it's not where you think it is, I suspect. For example, I suggest you write
File file = new File("src/main/resources/ExportHour.xls");
and then log file.getAbsolutePath(), to see what exact file it's using.
However, you should almost certainly not be using a FileInputStream anyway. It would be better to use something like:
InputStream inp = Foo.class.getResourceAsStream("/ExportHour.xls");
... for some class Foo which has a classloader which includes the resources you need.
(Or possibly /resources/ExportHour.xls", depending on your build structure.)
That way even when you've built all of this into a jar file, you'll still be able to open the resource.

What is the path to resource files in a Maven project?

In my Maven project, I have the following code in the main method:
FileInputStream in = new FileInputStream("database.properties");
but always get a file not found error.
I have put the file in src/main/resources and it is properly copied to the target/classes directory (I believe that is the expected behavior for Maven resources) but when actually running the program it seems it can never find the file. I've tried various other paths:
FileInputStream in = new FileInputStream("./database.properties");
FileInputStream in = new FileInputStream("resources/database.properties");
etc. but nothing seems to work.
So what is the proper path to use?
Based on "disown's" answer below, here was what I needed:
InputStream in = TestDB.class.getResourceAsStream("/database.properties")
where TestDB is the name of the class.
Thanks for your help, disown!
You cannot load the file directly like that, you need to use the resource abstraction (a resource could not only be in the file system, but on any place on the classpath - in a jar file or otherwise). This abstraction is what you need to use when loading resources. Resource paths are relative to the location of your class file, so you need to prepend a slash to get to the 'root':
InputStream in = getClass().getResourceAsStream("/database.properties");

Howto access properties file from Java EE web application?

I have created a dynamic web project within Eclipse. I created a properties file inside the src directory:
<project-root>/src/props.properties
I'm starting Tomcat via Eclipse in debug mode. Now I want to read the properties file from one of my POJOs, but I get a FileNotFoundException. The current path seems to be the Eclipse path.
I had a look into the web for solution, but none of them worked for me. Maybe I did something wrong. The code is like this:
File file = new File("props.properties");
FileReader reader = new FileReader(file);
properties.load(reader);
How should I acces the properties file?
Where should it be located?
Thanks in advance.
If its a web application then the properties will get deployed to WEB-INF/classes and can be loaded using the class loader
InputStream in = {NameOfClassWhereThisisInvoked}.class.getResourceAsStream("/props.properties");
properties.load(in);
in.close();
Actully that should work regardless of whether it is a webapp or not.
I'm assuming src is defined as a source folder
There is another way of doing this as follows:
File file = new File(session.getServletContext().getRealPath("/") + "props.properties");
Instead of "props.properties" you could give any path relative to the "WebContent" folder of your eclipse web-application project.
here is the correct way to load properties file from anywhere in the classpath
private Properties getPropertiesFromClasspath(String propFileName)
throws IOException
{
Properties props = new Properties();
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream == null)
{
throw new FileNotFoundException("property file '" + propFileName
+ "' not found in the classpath");
}
props.load(inputStream);
return props;
}
You can create a singleton class to load properties in memory on first time access and later use them via a static method. A complete example of this is available at
http://bharatonjava.wordpress.com/2012/09/12/using-properties-file-in-java-application/
Kepp ur Properties file in src folder and the following code is enough to read the properties file
**File file = new File("./src/config.properties");
FileReader reader = new FileReader(file);
prop.load(reader);
System.out.println(prop.getProperty("directorypath"));**
Is your project set to build automatically? If so (or you're building manually), check whetherprops.properties appears in your project's output folder (in Eclipse this is usually "bin" but may be WebRoot or something else, depending on how your project is set up).
When a project builds, it should copy over config files as well as your compiled classes, JSPs etc. However, I believe that file readers, by default, use the JVM's home directory for their source. In Eclipse's case, this means that your props.properties file would have to be in the project root, i.e. not the "src" folder.

Categories

Resources