2

I am able to obtain an InputStream to a resource in my WEB-INF folder like this :

    ExternalContext externalContext = facesContext.getExternalContext();
    InputStream in = externalContext.getResourceAsStream("/WEB-INF/config.xml");

Now I'd like to edit this file during runtime but I don't know how to overwrite the file. Is there a better way than creating a FileOutputStream to the absolute path ? And even if not I'd still need a way to obtain the absolute path of the file (the absolute path to the WEB-INF folder).

nico1510
  • 596
  • 8
  • 28

1 Answers1

2

As to the concrete question, you can get the absolute path to the file as follows:

ExternalContext externalContext = facesContext.getExternalContext();
String realPath = externalContext.getRealPath("/WEB-INF/config.xml");
FileOutputStream output = new FileOutputStream(realPath);
// ...

As to the concrete funcitonal requirement, there are however 2 possible major problems:

  1. getRealPath() will return null when the container is configured to expand WAR file in memory instead of on disk. There's then no means of a physical disk file system path. There's no way to get a "file path" to the location in memory.

  2. Even if it returns a valid path, all changes made in the expanded WAR structure on the local disk file system will get lost whenever you redeploy the WAR, or even in some server configurations also when you just restart the server. The simple reason is that those changes are not contained in the original WAR file. You'd basically need to extract the WAR, make the change in there, pack the WAR again and trigger the redeploy of the server. This makes no sense during runtime.

In other words, you're looking for the solution in the wrong direction. You need to prepare a fixed local disk file system path and read/write from/to it instead. An alternative is to use a SQL database instead or very maybe java.util.prefs.preferences.

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452