I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json.
Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:
public class CommonTestUtility {
public static String getFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
}
Now while calling this function as
class ServerTest {
#Test
void test_loadResource() {
String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}
}
, It's giving me the error as:
CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.
I tried to include the src/test/resources/ in the run configuration
of Junit ServerTest.java, but still it's not able to find out the
resource
How to resolve this issue?
https://mkyong.com/java/java-read-a-file-from-resources-folder/
This above link might be helpful.
The getResource() method return an URI you need to change
.getFile() function to. toURI().
Simple code
private File getFileFromResource(String fileName) throws URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
I recreated the same scenario you describe and your code works for me.
Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.
Related
Is it possible to access Assets inside the Java code in Play Framework? How?
We access assets from the scala HTML templates this way:
<img src="#routes.Assets.versioned("images/myimage.png")" width="800" />
But I could not find any documentation nor code example to do it from inside the Java code. I just found a controllers.Assets class but it is unclear how to use it. If this is the class that has to be used, should it maybe be injected?
I finally found a way to access the public folder even from a production mode application.
In order to be accessible/copied in the distributed version, public folder need to be mapped that way in build.sbt:
import NativePackagerHelper._
mappings in Universal ++= directory("public")
The files are then accessible in the public folder in the distributed app in production form the Java code:
private static final String PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH = "public/images/";
static File getImageAsset(String relativePath) throws ResourceNotFoundException {
final String path = PUBLIC_IMAGE_DIRECTORY_RELATIVE_PATH + relativePath;
final File file = new File(path);
if (!file.exists()) {
throw new ResourceNotFoundException(String.format("Asset %s not found", path));
}
return file;
}
This post put me on the right way to find the solution: https://groups.google.com/forum/#!topic/play-framework/sVDoEtAzP-U
The assets normally are in the "public" folder, and I don't know how you want to use your image so I have used ImageIO .
File file = new File("./public/images/nice.png");
boolean exists = file.exists();
String absolutePath = file.getAbsolutePath();
try {
ImageInputStream input = ImageIO.read(file); //Use it
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("EX = "+exists+" - "+absolutePath);
I am trying to grab a file (in this case an image) from the file system and display it. I can do it from a resources subdirectory just fine, but when I try to go to the file system it is giving me a FileNotFound exception.
java.io.FileNotFoundException: file:\Y:\Kevin\downloads\pic_mountain.jpg (The filename, directory name, or volume label syntax is incorrect)
All the rest of my code is vanilla spring boot that was generated from the Initialize. Thanks.
#RestController
public class ImageProducerController {
#GetMapping("/get-text")
public #ResponseBody String getText() {
return "Hello World";
}
#GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage(HttpServletResponse response) throws IOException {
FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
// ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
System.out.println(imgFile.getURL());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
}
}
from the docs:
public FileSystemResource(String path)
Create a new FileSystemResource from a file path
the constructor expects a path-part of the url, so in your case only Y:/Kevin/downloads/pic_mountain.jpg
so you should try to use it this way:
FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");
Btw. could it be, that you miss "Users" in your path? -> Y:/Users/Kevin/downloads/pic_mountain.jpg
I'm trying to unmarshal my xml file:
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
But I get this errors:
java.io.FileNotFoundException: null (No such file or directory)
Here is my structure:
Why I can't get files from resources folder? Thanks.
Update.
After refactoring,
URL url = this.getClass().getResource("/xmlToParse/companies.xml");
File file = new File(url.getPath());
I can see an error more clearly:
java.io.FileNotFoundException: /content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml (No such file or directory)
It tries to find WEB-INF/classes/
I have added folder there, but still get this error :(
I had the same problem trying to load some XML files into my test classes. If you use Spring, as one can suggest from your question, the easiest way is to use org.springframework.core.io.Resource - the one Raphael Roth already mentioned.
The code is really straight forward. Just declare a field of the type org.springframework.core.io.Resource and annotate it with org.springframework.beans.factory.annotation.Value - like that:
#Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;
To obtain the needed InputStream, just call
companiesXml.getInputStream()
and you should be okay :)
But forgive me, I have to ask one thing: Why do you want to implement a XML parser with the help of Spring? There are plenty build in :) E.g. for web services there are very good solutions that marshall your XMLs into Java Objects and back...
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
you are suppose to give an absolute path (so add a loading ´/´, where resource-folder is the root-folder):
public Object convertFromXMLToObject(String xmlfile) throws IOException {
FileInputStream is = null;
File file = new File(String.valueOf(this.getClass().getResource("/xmlToParse/companies.xml")));
try {
is = new FileInputStream(file);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
In order to list file contents of a specific directory on classpath I'm using the new FileSystem and Path features of Java 7. In one deployment the directory is stored on file system, directly. In another deployment it is stored into a JAR file.
My approach works fine with JAR files: I create a FileSystem object which refers to the JAR file and access the content via Path object.
...
URI dir = ...
String[] array = dir.toString().split("!");
try (final FileSystem fs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap<String, Object>()))
{
final Path directory = fs.getPath(array[1]);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory))
{
...
Due to the dir object has following value, it works:
jar:file:/C:/Users/pax/.../Detector-1.0.jar!/org/.../destinationdir
But in the other environment the destination directory is stored on file system, directly. dir object contains the value:
file:/C:/Users/pax/.../destinationdir
FileSystems.newFileSystem(...) always throws following exception for / and file:/C:/Users/pax/.../destinationdir as URI:
java.lang.IllegalArgumentException: Path component should be '/'
at sun.nio.fs.WindowsFileSystemProvider.checkUri(WindowsFileSystemProvider.java:68)
How do you use FileSystem.newFileSystem for destinations on file system?
Is there a better approach in order to list the directories content independently from its specific kind of storage (file system or JAR file)?
Following question's resolution tackles the issue ("destination on file system" versus "destination in JAR file") by try-catch approach: NIO2: how to generically map a URI to a Path?
This utility method tries to obtain a correct Path instance. But there may occur a further problem: If this destination resource is contained by a JAR file (instead of file system) then you can only access the resource via its associated FileSystem instance which must not be closed! So, your helper method needs to return the Path object as well as the FileSystem instance (only required if it's not on file system directly). The invoker has to close the FileSystem object, manually:
public static PathReference getPath(final URI resPath) throws IOException
{
try
{
// first try getting a path via existing file systems
return new PathReference(Paths.get(resPath), null);
}
catch (final FileSystemNotFoundException e)
{
/*
* not directly on file system, so then it's somewhere else (e.g.:
* JAR)
*/
final Map<String, ?> env = Collections.emptyMap();
final FileSystem fs = FileSystems.newFileSystem(resPath, env);
return new PathReference(fs.provider().getPath(resPath), fs);
}
}
The wrapper class PathReference should implement AutoClosable so that it can be used in try block:
public class PathReference implements AutoCloseable
{
...
#Override
public void close() throws Exception
{
if (this.fileSystem != null)
this.fileSystem.close();
}
public Path getPath()
{
return this.path;
}
public FileSystem getFileSystem()
{
return this.fileSystem;
}
}
This makes the release of the FileSystem instance a bit more transparent:
...
try (final PathReference fileObj = SignatureUtils.getPath(file))
{
...
try (InputStream fileStream = Files.newInputStream(fileObj.getPath()))
{
...
i want to open a file and return its content. Although it is in the same directory like the class that wants to open the file, the file can't be found. Would be cool if you could help me solving the problem.
Here is the code:
#GET #Produces("text/html") #Path("/{partNO}/") #Consumes("text/html")
public String getPartNoResponseHTML(#PathParam("partNO") String parID) throws WebApplicationException {
PartNoTemplate partNo = getPartNoResponse(parID);
String result = "";
try {
result = readFile(PART_NO_TEMPLATE_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
return e.getMessage() + e.toString();
// throw new WebApplicationException(Response.Status.NOT_FOUND);
} finally {
result = result.replace("{partNO}", parID);
result = result.replace("{inputFormat}", partNo.getFormat().toString());
}
return result;
}
I guess it can't find the file, because its running on tomcat. I'm also using Jersey and JAX-RS. Thank you for your help,
Maxi
If the file is inside the application WAR (or in a jar) you can try by using
InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");
Your problem is similar (I think) with How can I read file from classes directory in my WAR?
Try to get the path of the file from ServletContext.
ServletContext context = //Get the servlet context
In JAX-RS to get servlet context use this:
#javax.ws.rs.core.Context
ServletContext context;
Then get the file from your web application:
File file = new File(context.getRealPath("/someFolder/myFile.txt"));
You don't post the code that actually tries to read the file, but assuming the file is in the classpath (as you mention it's in the same directory as the class) then you can do:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
See here