Alex Naughton
Alex Naughton

Reputation: 165

How do I get the path to a file in Java Servlet

I'm creating a simple web app on my local machine using XAMPP. Basically, I want to check if a file exists, but I do not know how to get the path of the file.

If I do the following, it will say that this file exists, which is true.

String path = "C:\\Users\\user\\Desktop\\ProjectName\\web\\files\\filename.txt";

However, this path is no good if I move the project from one computer to another, as the path won't be the same. What I'm asking is, what is the shortcut that I can use to get the location of the file. I know in PHP it would be something like

path = base_url()."files\filename.txt";

I can't really put into words what I am trying to ask, but I think people will get the idea.

Edit:

I'm using Netbeans too if that makes any difference.

Upvotes: 4

Views: 3414

Answers (1)

Remo Liechti
Remo Liechti

Reputation: 192

The easiest to find where your path really is is to do the following, because every application server handles the file handles a bit differently:

System.out.println(new File(".").getAbsolutePath());

Like this, you open a file handle on the current directory and you know where you are located. From there on, you know how to navigate. Be aware, that this is a dirty trick to find your starting point only. Depending on what you want to achieve, you are better of using the application server infrastructure to deal with files.

In case you are wondering on how to get the base url which you refered to, this one is stored in the request context of your servlet request:

public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
String url = request.getRequestURL().toString();

Upvotes: 2

Related Questions