0

I have a file in package '\src\main\resources\'. I want to read that file in a .java file which is located at 'src\main\java\com\xxxx\xxxx\services\'.When I run the following code,

File USER_DIRECTORY = new File( System.getProperty("user.dir") );
File DOCUMENT_DIRECTORY = new File( USER_DIRECTORY, "src/test/resources" );
File template = new File( DOCUMENT_DIRECTORY, "input.docx" );

I am getting value of USER_DIRECTORY as 'C:\workspace\apache-tomcat-7.0.70\bin' and DOCUMENT_DIRECTORY as 'C:\workspace\apache-tomcat-7.0.70\bin\src\test\resources'. The target file is not present in that location. If I run the same code in unit tests, I am getting right values. Can someone help me how to read a file from different package? Please let me know if additional information is required to better understand the issue.

choom
  • 45
  • 1
  • 11

2 Answers2

1

In Maven/Gradle by default the resources which are in src\main\resources will be in the CLASSPATH.

So if you have a file named input.docx in src\main\resources you can read the file as follows

File documentFile = new File(SomeClass.class.getResource("/input.docx").toURI());

If the file is in subfolder like sec\main\resources\documents then use

File documentFile = new File(SomeClass.class.getResource("/documents/input.docx"));

Note: Replace the SomeClass with your class name.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • Thanks Karthikeyan Vaithilingam! The resource file is in different module. I am getting following value for documentFile. 'file:/C:/workspace/XXXXXProject/web/target/ROOT/WEB-INF/lib/docx-1.5.0-SNAPSHOT.jar!/input.docx'. Getting following error 'java.lang.IllegalArgumentException: URI is not hierarchical' – choom Sep 22 '16 at 05:09
0

Maven does not package any classes available in /src/test/*
Hence, at runtime, these files will not be available. If you do want them available, you can either modify your build path in maven (but that begs the question, why?), or, probably, it should be located in /src/main/resources

This will automatically made available. See also @Karthikeyan Vaithilingam 's answer. from there.

Koos Gadellaa
  • 1,220
  • 7
  • 17