None of the properties file is getting loaded in Servlet Application [duplicate] - java

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 5 years ago.
I'm preparing a servlet application and none of the properties file is getting loaded in application. Even though all the property files are residing in the same location.
Code:
Properties prop = new Properties();
InputStream input = getClass().getClassLoader().getResourceAsStream("ldap.properties");;
try{
logger.debug("Loading Properties File");
//input = new FileInputStream("ldap.properties");
// load a properties file
prop.load(input);
logger.debug("Retry Count is: " + Integer.parseInt(prop.getProperty("retry")));
System.out.println("Retry Count is: " + Integer.parseInt(prop.getProperty("retry")));
logger.debug("downTimeValue is: " + Integer.parseInt(prop.getProperty("downTimeValue")));
retry = Integer.parseInt(prop.getProperty("retry"));
downTimeValue = Integer.parseInt(prop.getProperty("downTimeValue"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Error:
[#|2018-01-22T15:34:27.313+0530|SEVERE|oracle-glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=64;_ThreadName=Thread-2;|log4j:WARN No appenders could be found for logger (com.amdocs.LDAPKit).|#]
[#|2018-01-22T15:34:27.314+0530|SEVERE|oracle-glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=64;_ThreadName=Thread-2;|log4j:WARN Please initialize the log4j system properly.|#]
[#|2018-01-22T15:34:27.314+0530|SEVERE|oracle-glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=64;_ThreadName=Thread-2;|log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.|#]
[#|2018-01-22T16:02:37.033+0530|WARNING|oracle-glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=67;_ThreadName=Thread-2;|StandardWrapperValve[com.amdocs.LDAPKit]: PWC1406: Servlet.service() for servlet com.amdocs.LDAPKit threw exception
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.amdocs.LDAPKit.doPost(LDAPKit.java:133)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)

I highly recommend to transform your project to a maven project so that it will handle dependencies and build your project.
After that, move your properties files to resources folder because getClass().getClassLoader().getResourceAsStream("ldap.properties"); looks for files in resources folder.
Your project structure should look like this

Related

java.io.IOException- can't create file in build folder [duplicate]

This question already has answers here:
File loading by getClass().getResource()
(2 answers)
How to use SQLite database inside jar file?
(4 answers)
Where should I place my sqlite database in my java maven project
(1 answer)
Closed 8 months ago.
Java project build by Gradle.
I want to create file in \build\resources\main\db\sqlite\insert-data.sql
I try this:
protected File getDestinationFile(String baseDir) {
try {
URL testURL = ClassLoader.getSystemClassLoader().getResource("db/sqlite");
String pathName = testURL + "/" + DEFAULT_FILE_NAME_INSERT_DATA;
logger.debug("pathName = " + pathName);
File newFile = new File(pathName);
newFile.createNewFile();
return newFile;
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
}
But I get error on runtime:
[17.06.2022 00:19:38.223] MyClass.getDestinationFile(SQLiteStrategy.java:170) ERROR:
java.io.IOException:
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)

How to load a properties file from classpath in Java [duplicate]

This question already has answers here:
How can I save a file to the class path [closed]
(6 answers)
Closed 7 years ago.
I'm trying to create a config file to save the username and ip data for a client inside the classpath, as in a resources folder in the project. I'm able to retrieve the properties like this:
public String getProperty(String property){
String result = null;
try{
InputStream inputStream = this.getClass().getResourceAsStream(filename);
Properties properties = new Properties();
if (inputStream != null){
properties.load(inputStream);
System.out.println(this.getClass().getResource(filename).toString());
}else {
System.out.println("File not found or loaded: "+filename);
}
result = properties.getProperty(property, null);
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
But I also want to be able to set those values which I can get from the file, so to attempt to do that, I use this method:
public void setProperty(String property, String value){
try{
OutputStream out = new FileOutputStream(this.getClass().getResource(filename).getFile());
Properties properties = new Properties();
properties.setProperty(property, value);
properties.store(out, "Optional comment");
out.close();
}catch (Exception e){
System.out.println("Unable to load:"+filename);
e.printStackTrace();
}
}
However, running that method gives me the following error:
java.io.FileNotFoundException: file:/home/andrew/Documents/Programming/Executable-JARs/SchoolClient.jar!/client-config.properties (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at com.andrewlalis.utils.DataSaver.setProperty(DataSaver.java:54)
at com.andrewlalis.MainClient.getNewIp(MainClient.java:173)
at com.andrewlalis.ClientWindow$4.mouseClicked(ClientWindow.java:142)
Now, I have confirmed that the file client-config.properties does exist, as I am able to read data from it, but it seems I'm unable to create an output stream for it. Why is that? Thank you in advance.
The problem I have is that I cannot open an output stream from the file in my classpath.
That property is inside your .jar-file. So your question should rather be "how to modify contents of the .jar file currently executing" which is not a good idea.
The main question here would be:
Do you need those values persisted?
If the values you set should stay active only while program run that's fine - just .setProperty(key, value); and all's fine.
If on the other hand you want those values to be persisted for the next start of the application, you'd might want to consider Preferences instead.

Error in file is :- java.io.FileNotFoundException: \files\storetime.txt (The system cannot find the path specified)

i am using eclipse for develop the java desktop application and working with file but got the above error
my code is as following please try to help me how to give path in eclipse and also get same problem to load image from the given task
i have put the "files" folder out side the "src" folder
how to give path dynamically
my code is ass following
public int getTimeId()
{
LOG.info("The File name is :- " + fileName);
LOG.info("The path is :- ");
int count=0;
FileInputStream fileInputStream;
ObjectInputStream objectInputStream;
try
{
fileInputStream=new FileInputStream("/files/storetime.txt");
objectInputStream=new ObjectInputStream(fileInputStream);
while(objectInputStream.readObject()!=null)
{
count++;
}
}
catch(IOException e)
{
System.out.println("Error in file is :- " + e);
} catch (ClassNotFoundException e) {
System.out.println("Error in class not found :- " + e);
}
return count;
}
}
You are providing the absolute path by prep-ending / in the path. It means root directory in Unix file system. so, you have to give a relative path of the file from the current directory.You can put files directory in the root directory of your project folder and use
fileInputStream=new FileInputStream("files/storetime.txt");
So, it will be picked up
Use FileInputStream(new File("files/storetime.txt")); don't use /file -> it will check for /file partition in linux as /root

Can't load Properties from JAR

For a few days now, I have been trying to get my Java project to load some properties from a file located in it's JAR file. However, I am constantly getting a null pointer when trying to load in the file.
The folder hierarchy has the properties file in /data, and all the source files in /emp/**/** ...
Code
Properties defaultProps = new Properties();
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("data/build_info.properties");
//InputStream in = new URL("file:data/build_info.properties").openStream();
defaultProps.load(in);
in.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
} catch (NullPointerException e){
Log.E("NPE- Properties not loaded", "properties");
revision = "Properties file not found";
}
if (defaultProps.getProperty("build.major.number") == null) {
Log.W("Properties not loaded", "properties");
revision = "Properties file not found";
} else {
Log.V("Properties Loaded Successfully", "properties");
revision = "Version: " + defaultProps.getProperty("build.major.number")
+ "." + defaultProps.getProperty("build.minor.number") + " "
+ "Revision: "
+ defaultProps.getProperty("build.revision.number");
}
If data is in the root of your jar, and if build_info.properties is inside the data directory in the jar, and if the jar is on the classpath, then getClass().getClassLoader().getResourceAsStream("data/build_info.properties"); will find that properties file. You could also use getClass().getResourceAsStream("/data/build_info.properties");.
Peculiarities can arise if getClass() returns a class loaded by a classloader different than the one that has your jar on its classpath.
You could alternatively try --
Thread.currentThread().getContextClassLoader().getResourceAsStream("data/build_info.properties");
I had the same issue with a dead-simple console application. Eventually I found a hint at https://stackoverflow.com/a/1464541/1792291 and I made my console app into a swing app, and suddenly everything worked.
The explanation in the link above does make some sense: since the console app gets its properties (including CLASSPATH) once when the shell is created, it won't know about the classpath defined during/for/by the JVM.

how do i create http visible files from java web application?

How can I create files visible by http protocol from java web application in web/myFiles folder ?
Is this even possible ?
for the following code :
String realPath = getServletContext().getRealPath("/");
System.out.println(realPath);
try {
BufferedWriter out = new BufferedWriter(new FileWriter( realPath + "\\myFiles\\test.txt"));
out.write("aString\nthis is a\nttest");
out.close();
} catch (IOException e) {
System.out.println("Exception " + e);
}
i keep getting the error :
Exception java.io.FileNotFoundException: C:\Documents and Settings\Andrei\My Documents\NetBeansProjects\SemanticCashUpV1.0\build\web\myFiles\test.txt (The system cannot find the path specified)
Yes possible,
You need to create file in public web area.
near to WEB-INF Dir.
you can get path to public web space by
request.getServletContext().getRealPath("/");

Categories