Skip to main content

creating a file from managed bean.

3 replies [Last post]
samanosuke31
Offline
Joined: 2010-08-16
Points: 0

Hi, my cuestion is:
I'm trying create a file from a managed bean of my jsf 2.0 aplication. the problem is that i want to create the file in the root of my web aplication or in any othe folder under the root, but the file is created somewhere else in the server.
i'm using glassfish v3.

when i use netbeans to deploy and run the aplication the file is created in domains/mydomain

and when i deploy it manualy the file is created in domains/mydomain/config

this is the code of a bean made for testig that:

@ManagedBean
@RequestScoped
public class Mybean {

public Mybean() {
}
public String createmyfile(){
File f = new File("testfile.txt");
try{
f.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
return "index";
}

}

Message was edited by: samanosuke31

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
manuelbernhardt
Offline
Joined: 2010-07-15
Points: 0

Hello samanosuke31,

to my knowledge, the servlet standard defines a way to get the path of a webapp on the disk.

http://download.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

i.e. if I'm not mistaken you should be able to get the path on disk via

[code]servletContext.getRealPath("/");[/code]

In order to fetch the servletContext from Faces, you can do

[code]ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext();[/code]

I hope this helps,

Manuel

samanosuke31
Offline
Joined: 2010-08-16
Points: 0

hello Manuel, thank you for your answer. The problem is solved now. but I made a modification since the original code you gave me did not work. your code throws the following exception:
java.lang.ClassCastException: com.sun.faces.context.ExternalContextImpl cannot be cast to javax.servlet.ServletContext

so I used the following line to get the real path of my root:

String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");

manuelbernhardt
Offline
Joined: 2010-07-15
Points: 0

Hi,

> hello Manuel, thank you for your answer. The problem
> is solved now. but I made a modification since the
> original code you gave me did not work. your code
> throws the following exception:
> java.lang.ClassCastException:
> com.sun.faces.context.ExternalContextImpl cannot be
> cast to javax.servlet.ServletContext

sorry, I forgot the last bit, should've been

[code]FacesContext.getCurrentInstance().getExternalContext().getContext()[/code]

but indeed you can now use getRealPath() directly on the ExternalContext, cool

Manuel