Does anyone knows how to read a file from the resource folder when the application is running on the AWS Elasticbeanstalk?
Please see code below:
Resource resource = new ClassPathResource("application.properties");
File file = resource.getFile();
Map propsMap = PropertyUtil.readProperties(file);
This is the error message:
java.io.FileNotFoundException: class path resource [application.properties] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/var/app/current/application.jar!/BOOT-INF/classes!/application.properties"
Thank you in advance.
You should probably just change your PropertyUtil to be able to read from the InputStream:
Properties properties = new Properties();
try (InputStream stream =
new ClassPathResource("application.properties").getInputStream()) {
properties.load(stream);
}
Properties class is already a Map implementation so you wouldn't need to change any other code.
Related
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.
I get the error "java.io.FileNotFoundException: AuthKey_7RHM5B8NS7.p8 (No such file or directory)", the file is clearly in my directory and I am using the relative path for the file. Here is my projects directory.
Project directory Image
final ApnsClient apnsClient = new ApnsClientBuilder()
.setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setSigningKey(ApnsSigningKey.loadFromPkcs8File(new File("AuthKey_7RHM5B8NS7.p8"),
"GL87ZNESF6", "7RHM5B8NS7"))
.build();
As you are trying to fetch file from resource folder hence you need to specify path for that.
File file = new File(getClass().getResource("/AuthKey_7RHM5B8NS7.p8").getFile());
or to get the URL
URL res = getClass().getClassLoader().getResource("AuthKey_7RHM5B8NS7.p8");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
You should not use the ApnsSigningKey.loadFromPkcs8File method but instead use the loadFromInputStream method.
The reason is that you are using a resource - and if you build a JAR file from your code, as is often done, your resource will be inside the JAR file and you will not be able to get a File object that points to it.
Code:
InputStream in = getClass().getResourceAsStream("/AuthKey_7RHM5B8NS7.p8");
final ApnsClient apnsClient = new ApnsClientBuilder()
.setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setSigningKey(ApnsSigningKey.loadFromInputStream(in, "GL87ZNESF6", "7RHM5B8NS7"))
.build();
in.close();
I am reading properties file to get a file path as below.
String result = "";
InputStream inputStream = null;
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = GetPropertyValues.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
The properties file has the path specified like below.
configSettingsFilePath = C:\\\\ConfigSetting.xml
Now I get this below exception when I run my code saying file is not found.
Creating instance of bean 'configSettingHelper'
configSettingsFilePath = C:\ConfigSetting.xml
2017-09-18 14:47:00 DEBUG ConfigSettingHelper:42 - ConfigSettingHelper :: ConfigSetting File:configSettingsFilePath = C:\ConfigSetting.xml
javax.xml.bind.UnmarshalException
- with linked exception:
[java.io.FileNotFoundException: C:\Java\eclipse\eclipse\configSettingsFilePath = C:\ConfigSetting.xml (The filename, directory name, or volume label syntax is incorrect)]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
Instead of reading the path from properties file, if I directly use "C:\ConfigSetting.xml" in the code, it reads the file.
Can you please suggest what I should use in the properties file to specify the path?
Reading the file only fails when the .jar is running.
Running the app from within Netbeans is fine. (Different path)
Also, the path is coming from
URL resourceURL = MyClass.class.getResource("mydir/myfile.txt");
Printing out the path is perfect.
Also, a mypicture.gif in the very same directory loads fine:
ImageIcon mypicture = new ImageIcon(imageURL, description)).getImage();
even when running the .jar. IE: the actual path must be fine.
It is only a text file I try reading via
InputStream input = new FileInputStream(fileName);
is when it fails - and only if it is in the jar.
This is probably because C:\ is not on the classpath. You're using getClassLoader() which presumably returns a ClassLoader.
According to the docs for ClassLoader#getResource:
This method will first search the parent class loader for the
resource; if the parent is null the path of the class loader built-in
to the virtual machine is searched. That failing, this method will
invoke findResource(String) to find the resource.
That file is in the root of the drive, which is not going to be on the classpath or the path of the class loader built-in to the VM. If those fail, findResource is the fallback. It's unknown where findResource looks without seeing the implementation, but it doesn't appear to pay attention to the C:.
The solution is to move the properties file into your classpath. Typically, you'd put property files like this in the src/main/resources folder.
I am not able to load the properties file into a java file. getting file not found exception. Can you please help here.
Java file location:
classes/com/my/location/for/javabased/utilities/convertor/servlet/GetProp.java
Properties file location:
classes/com/my/property/properties/Config.properties
My code:
Properties inputParams = new Properties();
FileInputStream in = new FileInputStream("classes/com/my/property/properties/Config.properties");
inputParams.load(in);
in.close();
Getting File not found exception
I prefer reading the property file in class like this
public class SomeClass{
private static Properties someProperties = new Properties();
static{
someProperties.load(SomeClass.class.getResourceAsStream("/com/my/property/properties/Config.properties"));
}
Hope this helps.
The java class File (which is used by FileInputStream) is based on the file system path, either absolute, or relative to the current working directory. Both is mostly not under full control of the running application. If your resources can be found within the classpath (which from the point of view of the running application is always the same) you should use the resource loading mechanisme of your classloader (as Vijendra Kulhade pointed out in his answer).
I have created a java project in which I am using a properties file also which is created inside a java packgae named abcedf
so package name is abcdef which consists a class name abc.java and a property file named drg.properties ,now from class abc.java i am referring to that properties file as..
abc tt = new abc();
URL url = tt.getClass().getResource("./drg.properties");
File file = new File(url.getPath());
FileInputStream fileInput = new FileInputStream(file);
now this file is referred and my program runs successfully but when I am trying to make it executable jar then this property file is not referred
please advise what is went wrong while creating the property file.
Use
tt.getClass().getResourceAsStream("./drg.properties");
to access the property file inside a JAR. You will get an InputStream as returned object.
-------------------------------------------------
Here is an example to load the InputStream to Properties object
InputStream in = tt.getClass().getResourceAsStream("./drg.properties");
Properties properties = new Properties();
properties.load(in); // Loads content into properties object
in.close();
If your case, you can directly use, the InputStream instead of using FileInputStream
When you access "jarred" resource you can't access it directly as you access a resource on your HDD with new File() (because resource doesn't live uncompressed on your drive) but you have to access resource (stored in your application jar) using Class.getResourceAsStream()
Code will looks like (with java7 try-with-resource feature)
Properties p = new Properties();
try(InputStream is = tt.getClass().getResourceAsStream("./drg.properties")) {
p.load(is); // Loads content into p object
}