Properties keep driving me crazy. Can't save it! "FileNotFound" - java

these properties keep driving me crazy. I'm reading everywhere, that even loading the properties should be no problem by just using:
Properties p = new Properties();
p.load(new FileInputStream("filename.properties");
Though in my case it doest work. Java is not finding the file, which is located in the class directory! Thats why i HAD TO use it with the Assetmanager:
String defaultProfileProperties = "filename.properties";
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
final Properties properties = new Properties();
try {
InputStream inputStream = assetManager.open(defaultProfileProperties);
properties.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open " + defaultProfileProperties + " property file");
e.printStackTrace();
}
Putting the filename.properties in the assets-folder.
Well, now I simply can't save the properties-file by using .store(out,comment) ...
I tried using a FileOutputStream with the path set to either "filename.properties", or "assets/filename.properties". Neither of them worked. I even added a slash here and there, but nothing is helping! I'm not finding any tutorials on the web, nor ppl having the same problem!
Could you please just help me? I guess this is such a simple thing, but i'm not getting a clue how to ... blah

If you open a file with FileInputStream, then the starting directory (relative path) is based on the working directory when you started java, NOT the classpath. Opening a file with resources will reference the classpath entries.
Have you tried using a full path when using FileInputStream()? Try that and see if it works, and if it does, then you'll need to either set the working directory at start up and/or reference your file via relative path from the start directory.

Try this:
InputStream in = this.getClass().getResourceAsStream("filename.properties");
Properties p = new Properties();
p.load(in);

Related

No such file or directory when reading Properties File in Java from one Class but not another

I am trying to read a properties folder from this path with respect to the repository root:
rest/src/main/resources/cognito.properties
I have a Class CognitoData from this path: rest/src/main/java/com/bitorb/admin/webapp/security/cognito/CognitoData.java which loads the Properties folder using this code, and it runs fine:
new CognitoProperties().loadProperties("rest/src/main/resources/cognito.properties");
#Slf4j
public class CognitoProperties {
public Properties loadProperties(String fileName) {
Properties cognitoProperties = new Properties();
try {
#Cleanup
FileInputStream fileInputStream = new FileInputStream(fileName);
cognitoProperties.load(fileInputStream);
} catch (IOException e) {
log.error("Error occured. Exception message was [" + e.getMessage() + "]");
}
return cognitoProperties;
}
}
However, when I call CognitoData from a test class located in rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java , I get this error:
[rest/src/main/resources/cognito.properties (No such file or directory)]
Can anybody shed light on why this is happening?
File directory is not actually relative in that case. You need to provide appropriate file path for this. If you are already using spring boot, then
you can change your code to:
// this will read file from the resource folder.
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("cognito.properties");
cognitoProperties.load(inputStream);
Otherwise you need to provide the full absolute path. new CognitoProperties().loadProperties("/absolutepath/..../cognito.properties")
I don't know what you're using for testing, but I suspect that the working directory when you run tests is not the project root.
One solution is to use an absolute path instead:
/absolute/path/to/project/rest/src/main/resources/cognito.properties
Or maybe check what is the working directory during testing and see if it can be changed to the project root.

How to retrieve Database properties from Properties file using Tomcat in order to work on multiple machines [duplicate]

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 3 years ago.
I am working on a webapp using Maven and Java servlets. I'm trying to build a connection to my local Postgres Database by retrieving its credentials from a Properties file because I don't want to hard code them. For this im using FileInputStream in a "getProperties" general method. The problem is that i am using a Tomcat Server, so the project runs from the Tomcat directory, and I'm having trouble setting it so that my fellow programmers can run my app on their own machines without having to hardcode a directory. The final goal is to only have to change the file itself and never the code.
So i have a Properties file like this:
port = localhost
bdname = clothingdb
user = jmbs
pw = 123
and im trying to retrieve them like this:
String port = getProperties("port");
String bdname = getProperties("bdname");
String user = getProperties("user");
String pw = getProperties("pw");
Using this method:
public String getProperties(String propriedade)
{
String parametro = null;
try (InputStream input = new FileInputStream("svlocal.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
parametro = prop.getProperty(propriedade);
} catch (IOException ex) {
ex.printStackTrace();
}
return parametro;
}
For this i get the "File not found" error, because the project runs from the tomcat/bin directory and not from the
NetBeansProjects/bookstore/ directory where i need to have the Properties file.
My actual question is, how can i set the Properties file, so that when i send my project to someone else he only has to run it and change the credentials on the Properties file to access his own local database, and not having to change directories or hard code them on the
getProperties() method? Thanks in advance.
You can add the file in classpath and then load it as below,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("src/main/resources/svlocal.properties")
Ok, so, i was able to solve the problem using javaadict's suggestion but with a twist. I created a new directory in src/main/resources and added the properties file to it. then i used the following method:
public String getProperties(String propriedade){
String parametro = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try (InputStream input = classLoader.getResourceAsStream("svlocal.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
parametro = prop.getProperty(propriedade);
} catch (IOException ex) {
ex.printStackTrace();
}
return parametro;
}
It seems that because im using maven it recognizes the resources folder in src/main/resources and i was able to load the file just by using "svlocal.properties" in the getResourceAsSteam method.
Ty for the valuable suggestion javaaddict.

relative Path for file in struts 2 Webapplication

I've got one problem. I'm working on a web Application using Struts (Struts 2 Framework).
I created a Freemarker template file for every single user and save it in
webapps/mail/mailEn/customer.ftl
Now, when the page is called, I must look if a customer.ftl So I try looking after it in my java class like this:
( when i use local direcory path C://... it works)
MimeBodyPart textBodyPart = null;
try {
textBodyPart = new MimeBodyPart();
Configuration cfg = new Configuration();
//FileTemplateLoader ftl1 = new FileTemplateLoader(new File ("D:/Workspace//Projectname///web///styles/");
FileTemplateLoader ftl1 = new FileTemplateLoader (new File("\\mail\\mailEn")); TemplateLoader[] loaders = new TemplateLoader[] { ftl1 };
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
cfg.setTemplateLoader(mtl);
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template template = cfg.getTemplate("customerInfo.ftl");
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put("image1", "images/LOGO.jpg");
rootMap.put("recipient", "aaaa");
rootMap.put("address", "xxxx");
rootMap.put("contact", "yyyy");
rootMap.put("country", "uuuu");
rootMap.put("sender", "rrrrr");
Writer out = new StringWriter();
template.process(rootMap, out);
textBodyPart.setContent(out.toString(),Constants.TEXT_HTML);
}
With the absolute path (D:/....) it works without problems. But this can't be the
solution, because when Ive finished this web-app, I will have an war-file which will be put on a server and the absolute path will be wrong then. So I need a relative path which will always work!
I'm working with Eclipse at this moment. When I try to use the path above (/../.. ....),
the file I'm looking for can never be found. (I tried to go up to the home path of the
project and then to the folder mail, where the file is)
I tried out many different paths like ./web/mail/ , ../../../../../web/styles, and so on,
but I never found the file I was looking for.
If anyone could give me a hint what to do, I would be very grateful!
Thank you!
You should use WebappTemplateLoader (or maybe ClassTemplateLoader). FileTemplateLoader is not a good fit for this, as in theory you can't even know if the war file will be extracted on the server, and if it's not extracted, you surely won't have a directory to point to.
actully your file are getting stored in the temp folder (application server/os) so i suggest to you `
request.getRequestedURI() + "/" + FILE_PATH`
Say: you saved "file.txt" at "URL:PORT/file/file.txt" which refers to the tmp folder in fact and it gets deleted once the server is restarted or application undeployed. make sure the folder you are using to save is outside web-inf
Solution(adjustment)
I used request.getSession().getServletContext().getRealPath()
In a class for example MessageUtility i used
final private static String MAIL = ResourceBundle.getBundle("cfg_webapp").getString("mails.folder");
String mailpath = request.getSession().getServletContext().getRealPath(MAIL);
FileTemplateLoader ftl1 = new FileTemplateLoader(new File(mailpath));
In cfg_webapp.properties i defined
## Mails
mails.folder=mails
It gets the path from ----- src/main/webapps/mails/customer.ftl
thanks all.

Find relative path of java application

I have read all the other questions related to this in StackOverflow and I did not find any clear response.
To cut it short, I have an application that will store some files in a directory that I will use than to process them. I have intentions of moving my app in different places (other computers) so I need to have a relative path to work with so that I will not change that in each time.
Does anyone know how to get the relative path of the application (not the full path) so that I could use in this case? If what I am asking is not wright please tell me another way to achieve what I need. Thank you
Just use "./".
No matter what directory your application has been launched from, "./" will always return that directory.
For example:
new File("./") will return a file object pointed at the directory your java application has been launched from
new File("./myDirectory") will return a file object pointed at the myDirectory folder located in the directory your java application has been launched from
Here is one approach:
I believe you need to define the path of directory containing the files in a configuration/property file. You can change the path in the configuration file when you move your application or the directory containing the file. This is how your properties file(let's say config.properties) contents should be:
filesDirPath=\usr\home\test
And this what you should do in the code:
private void readConfig()
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the directory path property value
String flesDirPath = prop.getProperty("filesDirPath");
System.out.println("Files to be read are located in dir : " + flesDirPath );
} catch (IOException ex) {
ex.printStackTrace();
}
}

Read maven.properties file inside jar/war file

Is there a way to read the content of a file (maven.properties) inside a jar/war file with Java? I need to read the file from disk, when it's not used (in memory). Any advise on how to do this?
Regards,
Johan-Kees
String path = "META-INF/maven/pom.properties";
Properties prop = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream(path );
try {
prop.load(in);
}
catch (Exception e) {
} finally {
try { in.close(); }
catch (Exception ex){}
}
System.out.println("maven properties " + prop);
One thing first: technically, it's not a file. The JAR / WAR is a file, what you are looking for is an entry within an archive (AKA a resource).
And because it's not a file, you will need to get it as an InputStream
If the JAR / WAR is on the
classpath, you can do SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"), where SomeClass is any class inside that JAR / WAR
// these are equivalent:
SomeClass.class.getResourceAsStream("/abc/def");
SomeClass.class.getClassLoader().getResourceAsStream("abc/def");
// note the missing slash in the second version
If not, you will have to read the JAR / WAR like this:
JarFile jarFile = new JarFile(file);
InputStream inputStream =
jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
Now you probably want to load the InputStream into a Properties object:
Properties props = new Properties();
// or: Properties props = System.getProperties();
props.load(inputStream);
Or you can read the InputStream to a String. This is much easier if you use a library like
Apache Commons / IO
String str = IOUtils.toString(inputStream)
Google Guava
String str = CharStreams.toString(new InputStreamReader(inputStream));
This is definitely possible although without knowing your exact situation it's difficult to say specifically.
WAR and JAR files are basically .zip files, so if you have the location of the file containing the .properties file you want you can just open it up using ZipFile and extract the properties.
If it's a JAR file though, there may be an easier way: you could just add it to your classpath and load the properties using something like:
SomeClass.class.getClassLoader().getResourceAsStream("maven.properties");
(assuming the properties file is in the root package)

Categories