Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a file image in a war project

I´m doing a javaEE application and I´m using spring to inject my ejbs and WAS7, currently I´m running it in a windows environment altough in the end it will run in a unix environment. So I create a java class that acts as my controller for spring and I´m supposed to get some data from a jsp and turn it into an excel. So when I try to get an image from my web-content folder so I can put it into my excel y get file not found. This is what I´ve tried so far without success:

    String path = File.separatorChar + "img" + File.separatorChar +  File.separatorChar + "logoCorporativo.jpg";
    System.out.println(path);

    try {
        FileInputStream fis = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

and

        String path = File.separator + "img" + File.separator +  File.separator + "logoCorporativo.jpg";
        System.out.println(path);

    try {
        FileInputStream fis = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I found that when I typped "http://localhost:9080/AdminMapasWeb/img/logoCorporativo.jpg" into my browser I can see the image.

Does anyone am I getting a FileNotFound Exception??? Thanks in advance.

like image 581
linker85 Avatar asked Nov 24 '25 12:11

linker85


2 Answers

Use

File file = getRequest().getServletContext().getRealPath("/img/logoCorporativo.jpg");

getRealPath convert a URL root relative path (using slashes "/") to a File. If the war does not unpack itself on deployment, getRealPath returns null.

like image 103
Joop Eggen Avatar answered Nov 27 '25 00:11

Joop Eggen


your file is packaged inside the *.war archive, so its not a standalone file on the file system (like it is in development) try using getClass().getClassLoader.getResourceAsStream() to get at it

like image 22
radai Avatar answered Nov 27 '25 01:11

radai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!