Carol
Carol

Reputation: 563

How to create a directory inside TOMCAT using Java?

I'm having troubles trying to create a directory inside my servlet application for saving an audio file. When I try to create it in the root directory: (C:/something) I have no trouble, but when I try to do it inside tomcat path I can't. Does any one know why? This is my code (I have to pass the target path by post, but I'm trying first with a path previous set).

public void doPost(HttpServletRequest request, 
                    HttpServletResponse response) throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    out.println("<HTML><HEAD></HEAD><BODY>");
    //nombreFichero = request.getParameter("nombreArchivo");
    //Ruta = request.getParameter("Destino");
    String destino = request.getParameter("Destino");
    String ruta2 = request.getContextPath();
    ruta2 += "/InformesAudio/";
    out.println("<P>Ruta para guardar: <B>" + destino + "</B></P>");
    out.println("<P>Ruta armada: <B>" + ruta2 + "</B></P>");

    File crearCarpeta = new File(destino);
    if(!crearCarpeta.exists())
    {
        crearCarpeta.mkdir();
        out.println("<P>La ruta de getContextPath modificada es: </P><P>" + destino + "</P>"
                    + "<P>CARPETA CREADA EXITOSAMENTE</P>");
    }

Thanks for your help buddies!! Have a nice day!! ;)

Upvotes: 0

Views: 2380

Answers (2)

Carol
Carol

Reputation: 563

I got it:

`

    public static String WEBAPP_ROOT;
    /**
    *       Initialize the servlet and set up some static variables :<br>
    */
    public void init() {
            WEBAPP_ROOT = getServletContext().getRealPath("/");
    }`

Then you

Upvotes: 1

Konza
Konza

Reputation: 2163

Try this.. Take the application root and then concatnate destination location. Also try using mkdirs() instead of mkdir(). It will create the parent directories if not present

File parent_dirs = new File(applicationRoot + destinationLoc);
if(!parent_dirs.exists()){
  parent_dirs.mkdirs();
}

Upvotes: 0

Related Questions