6

How do I get the directory where the a .java file is located? I don't want to use System.getProperty("user.dir"), because that gives me the directory of the executable, and not the directory of the .java file that contains this line of code.

I need this because I'm developing a JSP web-app, and the Java code creates a .csv file on the server side and I want to make it available on the client side, but I would need to place the csv file where the location of the .html files are so that they could be downloaded.

My current folder structure is like:

Java Resources ->src
->.java file

WebContent
->.html file

3
  • 5
    System.getProperty("user.dir") gives you the directory you launched the executable from. A .java file does not exist at runtime. Commented Oct 18, 2013 at 13:57
  • A .class file would exist, would I be able to use that somehow? Commented Oct 18, 2013 at 13:58
  • 3
    You're creating the file, so you have control of where it's created. Commented Oct 18, 2013 at 13:59

2 Answers 2

6

Try this for asking for your class

String s = getClass().getName(); int i = s.lastIndexOf("."); if(i > -1) s = s.substring(i + 1); s = s + ".class"; System.out.println("name " +s); Object testPath = this.getClass().getResource(s); System.out.println(testPath); 

this code snippet is from this.getClass().getResource("").getPath() returns an incorrect path

Sign up to request clarification or add additional context in comments.

Comments

6

The source file might as well not exist. Java is a compiled language, it runs compiled files, .java files aren't necessary and thus might not be there at runtime.

You can however, get the location of the .class file, as it was previously suggested.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.