Read relative static file in src - java

I have .tpl file containing some static content in a package in src.
e.g. src/A/B/C/test.tpl and i'm trying to read it from a class sibling that file (src/A/B/C/Test).
I can't find it in any way! FileReader throws FileNotFoundException.
SOLUTION: Class.getResource() works. Problem is about tpl extension which will not be compiled by default. IDEs have setting to add extensions to compile. I used .html instead of updating compiler settings.
Test.class.getResource("/A/B/C/test.html").getPath().replace("%20", " ")

You should use ClassLoader.html#getResourceAsStream
getClassloader().getResourceAsStream(resourcePath);

How about moving the file to src/main/resources and then trying something like -
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/test.tpl");
try {
context.getClassLoader().getResourceAsStream("test.tpl");
...
}
catch (IOException ex) {
ex.printStackTrace();
}

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.

Loading resources from another maven module with mvn exec:java doesn't work

I have a maven project with this structure:
parent
-----module1
--------src
------------main
-----------------java
----------------------Loader.java
-----------------resources
-------------------------file1.txt
-----module2
--------src
------------main
-----------------java
-------------------------CallLoader.java
So Loader.java, loads files1.txt. I call this class from CallLoader.java from module2. This is the code I used
In Loader.java,
private static File getResourceFile(String fileName){
try {
URL resource = GraphUtil.class.getClassLoader().getResource(fileName);
return new File(resource.getPath());
} catch (Throwable e) {
throw new RuntimeException("Couldn't load resource: "+fileName, e);
}
}
where fileName="file1.txt".
I get an error because the file absolute path looks like this:
file:/home/moha/.m2/repository/my/package/name/%7Bproject.version%7D/base-%7Bproject.version%7D.jar!/file1.txt
What exactly am I doing wrong?
Get the content of your file as a stream instead in order to be able to read your resource from a jar file which is the root cause of your issue. In other words use getResourceAsStream instead of getResource.
You can also return the URL instead of File then call openStream() later to read it if needed.
NB1: the URL will be of type jar:file/... which cannot be managed by the class File
NB2: To convert a URL into a File, the correct code is new File(resource.toURI())

Get "null" when I'm using getResourceAsStream to read properties file in Android Studio

I recently just start to using Android Studio for my programming study.
I've faced a problem today which is keep getting "null" when I using getResourceAsStream to read a properties file from JUNIT TEST.
I used to locate the .properties file under "src" directory when I was using Eclipse. But in Android Studio, it won't work.
Here is the code that part of a class called BeanFactory,:
private static Properties properties;
static {
properties = new Properties();
InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
try {
properties.load(is);
}catch (IOException e) {
e.printStackTrace();
}
}
In Eclipse, I located the the prop file under src, and it works just fine.
But in Android Studio, I've tried put the "bean.properties" file in several different directory. Such as /src, or/src/main/java, nothing worked out.
Where should I put the prop file? Is there any configurations that I should do for this?
Placing resources into assets is not acceptable in some cases. I solved this problem by packing required resourses into special jar file and placing this jar into libs directory.Thus you still can access them via standard Java technique.
There are two issues. In general resources are stored in a jar, with the compiled .class files.
getResource and getResourceAsStream are methods of a class. The resource is searched in the jar of this class (in general). So with inheritance getClass().getResource("...") might be dangerous.
The second, more grave pitfall is, that the path is relative to the package (directory) of the class, unless you use "/...".
Another way is to use ResourceBundle instead of Properties. ResourceBundle has a PropertiesResourceBundle for *.properties.
ResourceBundle properties = ResourceBundle.getBundle("bean");
try this:
1.put your own bean.properties file in app/src/main/assets
2.change you code to:
private static Properties prop;
static {
prop = new Properties();
try {
InputStream is = IWorkApplication.getInstance().getResources().getAssets().open("bean.properties", Context.MODE_PRIVATE);
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
PS.IWorkApplication.getInstance() is define in my own application class.
Hope to be useful

how to access resources(Excel file) in jar file

Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file when I am trying to access the file.
My project structure is:
Java_Project_Folder
- src_Folder
- resources_Folder(Containing excel file)
I am accessing the excel file like
FileInputStream file=new FileInputStream(new File(System.getProperty("user.dir")
+File.separator+"resources"+File.separator+"Excel.xlsx"));
I have tried accessing this file using getResourceAsStream like:
FileInputStream file=(FileInputStream) this.getClass().getResourceAsStream
("/resources/Excel.xlsx");
But i am getting in is null exception. whats wrong can anyone help?
I bet you have no package called resources in your project.
Trying to use Class.#getResourceAsStream is the way to go. But this method does not return a FileInputStream. It returns an InputStream wich is an interface.
You should be passing the absolute name of the resource
InputStream is = getClass().getResourceAsStream("my/pack/age/Excel.xlsx");
where the excel file is located in the directory
resources/my/pack/age
The first step is to include the excel file itself in your project. You can create a resources folder like you show, but to make sure this gets included in your jar, you add the resources folder in along with your source code files so that it gets built into the jar.
Then
InputStream excelContent = this.getClass().getResourceAsStream("/resources/Excel.xlsx");
should work. From one post at least, the leading forward slash may also mess things up if you use the ClassLoader.
getClass().getResourceAsStream("/a/b/c.xml") ==> a/b/c.xml
getClass().getResourceAsStream("a/b/c.xml") ==> com/example/a/b/c.xml
getClass().getClassLoader().getResourceAsStream("a/b/c.xml") ==> a/b/c.xml
getClass().getClassLoader().getResourceAsStream("/a/b/c.xml") ==> Incorrect
ref: getResourceAsStream fails under new environment?
Also in eclipse you can set the resources folder as a source folder like this:
in the properties of your eclipse project, go to java build path, select sources, and check to see if all needed source fodlers are added (as source folders). If some are missing, just add them manually using add sources... button
ref: Java Resources Folder Error In Eclipse
I tried this and it is working for me.
My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"
public class Test1 {
public static void main(String[] args) {
new Test1();
}
Test1(){
BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
try {
System.out.println((char)file.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileInputStream file= (FileInputStream)
this.getClass().getResourceAsStream("/resources/Excel.xlsx");
Why do you need FileInputStream? Use
InputStream is = getClass().getResourceAsStream..
Secondly use "resources/Excel.xlsx"
Thirdly when constructing file like this
new
File(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"Excel.xlsx"));
is hard to control slashes. use
new File("parent (userdir property)", "child (resources\Excel.xlsx)")

How do I use Java getResource() to get a resource from a parent directory?

I've tried numerous methods now, including FilenameUtils.normalize() from commons IO, but I can't seem to be able to get a resource in another folder to get a Java FXML file.
The code is the following
try {
root = FXMLLoader.load(getClass().getResource("../plugin/PluginSelection.fxml"));
} catch (IOException ex) {
Logger.getLogger(QueueOperationsController.class.getName()).log(Level.SEVERE, null, ex);
}
Where the desired FXML file is:
gui
dialogues
plugins
PluginSelection.fxml // desired file
dataset
QueueOperationsController // current class
How do I best get the desired file's URL?
Thank you!
You can get resources relative to the Class or the context root. In your example putting / at the start of the string if thats your package structure in your application. Try
getClass().getResource("/gui/dialogues/plugins/PluginSelection.fxml")
It seems to me that if we use .getResource only when searching in marked as resource folder. Otherwise, even if folder path is correct, but it's not marked as resource folder we'll got an error.
So, I do this way:
FileInputStream fileInputStream = new FileInputStream(new File("src/main/java/CRUD/bnkseekCRUD.fxml"));
Parent root = loader.load(fileInputStream);

Categories