3

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.

linker85
  • 1,601
  • 5
  • 26
  • 44

2 Answers2

3

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • @Joop `getRequest()` method is not compiled . i get compile time error saying method not found – Santhosh Sep 23 '14 at 10:18
  • @SanKrish he HttpServletRequest parameter if the code is in doGet/doPut/..., normally called `request` – Joop Eggen Sep 23 '14 at 10:31
  • @JoopEggen Actually my code is in the spring controller. so i tried `request.getServletContext().getRealPath("/img/logoCorporativo.jpg");` but still i get `NoSuchMethodError` – Santhosh Sep 23 '14 at 10:50
  • `request.getRealPath("...")` (from ServletRequest) should then do. Later versions provide a `getServletContext` which makes sense for a non-request function. – Joop Eggen Sep 23 '14 at 12:05
1

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

radai
  • 23,949
  • 10
  • 71
  • 115