This question already has answers here:
Reading a resource file from within jar
(15 answers)
Closed 6 years ago.
I am using maven web application.
The following is my project structure where I have placed my properties file.
The following is my code which I am using to read this file:
public static Properties loadProducerProperty() throws FileException {
Properties myProperties = new Properties();
try {
String resourceName = "newproperties.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
myProperties.load(resourceStream);
}
} catch (FileNotFoundException e) {
throw new FileException();
} catch (IOException e) {
throw new FileException();
}
return myProperties;
}
But I am getting FileNotFound Exception
I have gone through the following link and tried other things also but I am getting the same error :
Cannot load properties file from resources directory
What I am doing wrong here.
Thank you
Add a slash in front of the filename:
String resourceName = "/newproperties.properties"; // could also be a constant
Related
This question already has answers here:
How to load property file from classpath? [closed]
(2 answers)
Closed 6 years ago.
I have to access my .properties file from its class path. Currently I am accessing that from the resources folder directly. But now I want to acess that from the class path.
Current Code:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
try {
properties.load(new FileInputStream(
"src/resources/config.properties"));
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
rate.add(value);
}
}
}
Path of the file is :src/resources/config.properties
For deploying the code we are creating war file of the complete project.
Please suggest how can we get this file from the class path.
If your config.properties file reside on your same package of your java class then just use,
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
If you put the properties file in any package, then use the package name also
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/your_package_name/config.properties");
So the compete code be like,
try {
Properties configProperties = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
configProperties.load(inputStream);
}
catch(Exception e){
System.out.println("Could not load the file");
e.printStackTrace();
}
UPDATE :
For better understanding see the image.
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("somefile.properties")) {
properties.load(stream);
}
You can load file from classpath using this
this.getClass().getClassLoader().getResourceAsStream("config.properties");
If you are dealing with .properties files you should consider using ResourceBundle
This question already has answers here:
How to read properties file in web application? [duplicate]
(3 answers)
Closed 7 years ago.
My PC's operating system is Windows 7 64-bit.
I created a very simple Dynamic Web Project app in Eclipse:
I have a app.properties file in WEB-INF/classes directory with these properties:
DefaultMaximumBatchSize=1000
DAOFactory=MSSQLSERVER
I have a class AppProperties which reads the above file into a Properties object at startup using getResourceAsStream:
public class AppProperties {
private static final Properties APP_PROPERTIES;
static {
InputStream inputStream = null;
APP_PROPERTIES = new Properties();
try {
inputStream = AppProperties.class.getResourceAsStream("/WEB-INF/classes/app.properties");
System.out.println("AppProperties: inputStream=" + inputStream);
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
} catch (Exception e) {
System.out.println("AppProperties: Exception occured; e=" + e);
}
}
public static String getValue(String propertyName) {
if (propertyName == null || propertyName.equalsIgnoreCase(""))
return null;
else
return APP_PROPERTIES.getProperty(propertyName);
}
}
I have a listener class AppContextListener:
public class AppContextListener implements ServletContextListener {
public AppContextListener() {
}
public void contextInitialized(ServletContextEvent arg0) {
String defaultMaxBatchSize = AppProperties.getValue("DefaultMaximumBatchSize");
System.out.println("AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=" + defaultMaxBatchSize);
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
I deployed the app to JBoss 4.2.3, run the JBoss 4.2.3 and I get this output in server.log:
AppProperties: inputStream=java.io.FileInputStream#1adde645
AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=1000
Perfect.
I then deployed the same app to WildFly 8.2.1, run the WildFly 8.2.1 and I get this output in server.log:
AppProperties: inputStream=null
AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=null
What happened? What is the correct way to read properties file in WildFly from WEB-INF/classes directory?
Class.getResourceAsStream() looks for a resource in all of the directories and jars that constitute the classpath of the application.
So, if you start a java program with
java -cp foo;bar.jar com.baz.Main
And you use SomeClass.class.getResourceAsStream("/blabla/app.properties"), The classloader will look for the app.properties file under foo/blabla, and in the blabla directory of bar.jar.
Now, in a webapp, what constitutes the classpath of the webapp is
the directory WEB-INF/classes
all the jar files under WEB-INF/lib
So, if you call
AppProperties.class.getResourceAsStream("/WEB-INF/classes/app.properties")
the classloader will look for app.properties in
/WEB-INF/classes/WEB-INF/classes
<all the jar files of WEB-INF/lib>/WEB-INF/classes
The conclusion is that, to load an app.properties file located in WEB-INF/classes, what you need is
AppProperties.class.getResourceAsStream("app.properties")
JBoss shouldn't have worked.
Class.getResourceAsStream retrieves the resource from the classpath and the webapp root folder is not in the classpath.
The WEB-INF/classes folder is. Use getResourceAsStream("/app.properties"), and remember to close the stream:
private static final Properties APP_PROPERTIES = new Properties();
static {
try (InputStream inputStream = AppProperties.class.getResourceAsStream("/app.properties")) {
System.out.println("AppProperties: inputStream=" + inputStream);
if (inputStream != null)
APP_PROPERTIES.load(inputStream);
} catch (Exception e) {
System.out.println("AppProperties: Exception occured; e=" + e);
}
}
Now, if app.properties is always next to AppProperties.class, instead of at the root, make the name unqualified (remove the /). This will work even when your class is in a package (and it is in a package, right?).
Try
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream("/my.properties");`
I've exported my Java console application to a Jar file, but when I run the jar and call code that parses in a JSON file I get a java.lang.IllegalArgumentException
Does anyone know why the exception is being thrown when I run the program as a JAR? The parsing works fine when the application is run from Eclipse.
This is the exact error that is output when I execute the jar file and call the code that parses the JSON file:
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierar
chical
at java.io.File.<init>(Unknown Source)
at gmit.GameParser.parse(GameParser.java:44)
at gmit.Main.main(Main.java:28)
This is how the parsing is being done in my GameParser class:
public class GameParser {
private static final String GAME_FILE = "/resources/game.json";
private URL sourceURL = getClass().getResource(GAME_FILE);
private int locationId;
private List<Location> locations;
private List<Item> items;
private List<Character> characters;
public void parse() throws IOException, URISyntaxException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
// read from file, convert it to Location class
Location loc = new Location();
loc = mapper.readValue(new File(sourceURL.toURI()), Location.class);
Item item = mapper.readValue(new File(sourceURL.toURI()), Item.class);
GameCharacter character = mapper.readValue(new File(sourceURL.toURI()), GameCharacter.class);
// display to console
System.out.println(loc.toString());
System.out.println(item.toString());
System.out.println(character.toString());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the folder structure of my project:
The call getClass().getResource(GAME_FILE); will return a URL relative to this class. If you are executing your program from a JAR file, it will return a URL pointing to a JAR file.
Files in java can only represent direct filesystem files, not the ones in zip/jar archives.
To fix it:
Try to use getClass().getResourceAsStream() and use that instead of Files or
extract the files into some directory and use File in the same way as you are trying now.
This problem happen when you have two files with the same name,i mean in your project you have folder whith name "Images" and in your desktop you have other folder his name "images" automatically JVM choose desktop folder ,so if you want to confirm try to print your URI.Use this example to show your URI before creating your file
try {
URL location = this.getClass().getResource("/WavFile");
System.out.println(location.toURI());
File file = new File(location.toURI());
if (!file.exists()) {
System.out.println(file.mkdirs());
System.out.println(file.getAbsoluteFile());
}else
{
System.out.println(file.getPath());
}
} catch (Exception e) {
e.printStackTrace();
}
I have small app and I tested and packed to jar and am trying to run it but I have error.
Here is my project structure:
src
-kie.template
----- ServerMain.java ==> Class with main
-kie.template.util
---- PropUtils.java
---- server.properties
target
-kietemplate.jar
---- lib
In the main method, PropUtils class reads properties.
public class PropUtils {
private static final String PROPERTIES = "server.properties";
public static Properties load() {
Properties properties = new Properties();
InputStream is = null;
try {
properties.load(PropUtils.class.getResourceAsStream(PROPERTIES));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
return properties;
}
}
}
When I run the ServerMain class directly, it works fine. But after I packed it to jar and run, it shows error:
java -cp lib -jar kietemplate.jar
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at au.org.jeenee.kie.template.util.PropUtils.load(PropUtils.java:26)
The properties file is in the directory when I look into the jar file.
jar tf kietemplate.jar
Any help would be appreciated very much.
EDIT:
I changed the logic to read properties:
Properties properties = new Properties();
InputStream is = null;
try {
File file = new File("server.properties");
is = new FileInputStream(file);
properties.load(new InputStreamReader(is));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
It requires the properties file in parent directory of the jar file.
Your code works fine on my computer, both from the JAR and the filesystem.
A possible cause for that behaviour is the filesystem being case insensitive, but the jar file being case sensitive. But we really can't tell from the source code alone.
This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 6 years ago.
Hi all i am getting the error
Caused by: 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 richard.fileupload.FileUploadController.loadProp(FileUploadController.java:48)
... 60 more
whenever my properties class is called, this is the code
private Properties configProp = new Properties();
#PostConstruct
public void loadProp() {
System.out.println("Loading properties");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("../resources/config.properties");
try {
configProp.load(in);
System.out.println(configProp.getProperty("destinationPDF"));
System.out.println(configProp.getProperty("destination"));
System.out.println(configProp.getProperty("fileList"));
} catch (IOException e) {
e.printStackTrace();
}
}
private String destinationPDF = configProp.getProperty("destinationPDF");
public String destination = configProp.getProperty("destination");
private String username;
the error seems to be coming from this line :
InputStream in = this.getClass().getClassLoader().getResourceAsStream("../resources/config.properties");
try {
configProp.load(in);
what is causing this error and how can i solve it ?
the code above, should point to the properties file and then retrive the three variables values from it, it is not getting as far as the
System.out.println(configProp.getProperty("destinationPDF"));
System.out.println(configProp.getProperty("destination"));
System.out.println(configProp.getProperty("fileList
before i get the error
this is my directory structure
as you can see the properties file is in resources/, how would i get a link to this
EDIT :
ok so it works perfectly fine with the full link to the file :
configProp.load(new FileInputStream("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/WEB-INF/config.properties"));
but no matter where i put the file in the projet i can not get it to load at all, why is this ?
This line doesn't make sense:
this.getClass().getClassLoader().getResourceAsStream("../resources/config.properties")
ClassLoader.getResourceAsStream() loads a resource from the classpath, using a package path starting at the root package. And there is nothing above the root package.