Java Servlet - write data to file -


I have a servlet that uses the file with the data. The relative path of this file is in the web. Xml is the part of the code I have, which reads the data from the file:

  public class LoginServlet HttpServlet {Private map & lt; String, user data & gt; Users; Public Zero Init () throws ServletException {super.init (); String user file path = getServletContext () GetInitParameter ("user.access.file"); InputStream userFile = this.getClass (). GetResourceAsStream (userFilePath); Try {users = readUsersFile (userFile); } Hold (IOException e) {e.printStackTrace (); Embrace the new servlet (e); } .... ....} Private map & lt; String, user data & gt; ReadUsersFile (InputStream) throws IOException {BufferedReader fileReader = new BufferedReader (new InputStreamReader (is)); Maps & lt; String, user data & gt; Result = New Hashmap & lt; String, user data & gt; (); .... .... return result; }}   

Because this is servlet and it will not work on my PC only, I can not use the full path. Does anyone know how I can write data in this file Am, in the same way?

If the resource URL is conceptual for a full local disk file system path and it is writable, then You can use

  url = this.getClass () URL. GetResource (userFilePath); File file = new file (url.toURI (). GetPath ()); Outputstream output = new fileoptput (file); // ...   

However, it is not guaranteed to work on all environments.

Your best bet is actually a fixed and full local disk file system path, however common practice is to store structured data (username / password) in a database, not the file.

Comments