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.
Related
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");
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.
If I do this
fis = new FileInputStream(new File(".").getAbsolutePath() + "/sudoinput.txt");
Its trying to write to this location on the server. I am not sure if this is a writable
place.
FILE NAME (fos)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
FILE NAME (fis)::::::::::::::::::/opt/tomcat/temp/./sudoinput.txt
I wanted to write to
webapps/sudoku/WEB-INF/classes
which is basically
C:\Users...\git\sudo-project\sudo\src\main\resources
On Eclipse Windows 7 I get this
error
src\main\resources\sudoinput.txt (The system cannot find the path specified)
if I give
fis = new FileInputStream("src/main/resources/sudoinput.txt");
I have tried this too:
fis = new FileInputStream("src\\main\\resources\\sudoinput.txt");
but doesn't work.
how should I create a fileinputstream to be able to write to src/main/resources ?
please note that I am using eclipse windows to do dev and will be uploading the .war file on to a unix server if this changes the way in which the paths need to be specified.
The src/main/resources folder is a folder that is supposed to contain resources for your application. As you noted, maven packages these files to the root of your file so that you can access them in your library.
Have a look at the Maven documentation about the standard directory layout.
In certain cases, it is possible to write to the context but it is not a good idea to try it. Depending on how your webapp is deployed, you might not be able to write into the directory. Consider the case when you deploy a .war archive. This would mean that you try to write into the war archive and this won't be possible.
A better idea would be to use a temporary file. In that way you can be sure this will work, regardless of the way your web application is deployed.
Agree with Sandiip Patil. If you didn't have folder inside your resources then path will be /sudoinput.txt or in folder /folder_name/sudoinput.txt. For getting file from resources you should use YourClass.class.getResource("/filename.txt");
For example
Scanner scanner = new Scanner(TestStats.class.getResourceAsStream("/123.txt"));
or
Scanner scanner = new Scanner(new `FileInputStream(TestStats.class.getResource("/123.txt").getPath()));`
Also look at: this
You can keep the file created under resources and call .class.getresource(your_file_name_or_path_separated_with_forward_slash);
See if it works for you.
If you like to create files in webapps/sudoku/WEB-INF/classes which is in the end within the created WAR file which can be achieved by putting the files you want into src/main/resources/
This means in other words you need to create the folder src/main/resources and put the files you like into this directory.
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
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.