24

I have made a pure java app which tells me about number of files in a given directory. Now I set current directory by using the following code:

`File f = new File(".");`

After that I made an installer with its jar file and installed it in my windows 8 and then I add it to the windows right click drop down menu (context menu). When I launch it from the context menu it always tells me about the number of files in the directory where it is actually installed in however I want to know the number of files of that directory from where I am executing it.

So plz help me. I am a novice in this field and I don't want you to confuse me in current directory and the current execution directory. So I write this so long and hoping for a clean answer in very simple words.

Thanks

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Mohd Faizan Khan
  • 437
  • 1
  • 5
  • 16

5 Answers5

39

As Jarrod Roberson states in his answer here:

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

Example : GetExecutionPath

import java.util.*;
import java.lang.*;

public class GetExecutionPath
{
  public static void main(String args[]) {
    try{
      String executionPath = System.getProperty("user.dir");
      System.out.print("Executing at =>"+executionPath.replace("\\", "/"));
    }catch (Exception e){
      System.out.println("Exception caught ="+e.getMessage());
    }
  }
}

output for the above will be like

C:\javaexamples>javac GetExecutionPath.jav

C:\javaexamples>java GetExecutionPath
Executing at =>C:/javaexamples
Community
  • 1
  • 1
Ghostman
  • 6,042
  • 9
  • 34
  • 53
  • 2
    `System.getProperty("user.dir")` and `new File(".")` [usually return the same value](http://docs.oracle.com/javase/7/docs/api/java/io/File.html). So why would this work, while `new File(".")` doesn't, according to the question? – mthmulders Jul 30 '13 at 06:39
  • 1
    Again, you can't simply throw a link at the end of an answer where you've copied someone else's wording. You must explicitly quote the copied language so that people know it isn't your original contribution. – Brad Larson Jul 31 '13 at 20:17
9

You can do some crazy stuff:

String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
absolute = absolute.substring(0, absolute.length() - 1);
absolute = absolute.substring(0, absolute.lastIndexOf("/") + 1);
String configPath = absolute + "config/file.properties";
String os = System.getProperty("os.name");
if (os.indexOf("Windows") != -1) {
    configPath = configPath.replace("/", "\\\\");
    if (configPath.indexOf("file:\\\\") != -1) {
        configPath = configPath.replace("file:\\\\", "");
    }
} else if (configPath.indexOf("file:") != -1) {
    configPath = configPath.replace("file:", "");
}

I use this to read out a config file relativ to execution path. You can use it also to get execution path of your jar file.

sk2212
  • 1,688
  • 4
  • 23
  • 43
  • 1
    This actually answers the question. The higher-rated answers answer a question they think is more useful. – arcy Sep 09 '18 at 12:25
7

The following may help you

  System.getProperty("user.dir")

This will return you the path as a string

Karthikeyan
  • 2,634
  • 5
  • 30
  • 51
  • yes man i have done this too, and obviously i got the path in string but i want to know the path of that directory from where i am executing it not of that dirctory where it is installed in. – Mohd Faizan Khan Jul 30 '13 at 06:22
  • @Mohd Faizan Khan, i am not sure on your requirement.Do you the installation path in prior to execution ? – Karthikeyan Jul 30 '13 at 06:39
  • `System.getProperty("user.dir")` and `new File(".")` [usually return the same value](http://docs.oracle.com/javase/7/docs/api/java/io/File.html). So why would this work, while `new File(".")` doesn't, according to the question? – mthmulders Jul 30 '13 at 06:39
0

There are a couple of different things you might be interested:

  • Get current working directory: String workingDir = System.getProperty("user.dir");

  • Get class loader path: URL resource = classLoader.getResource("/");

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • `System.getProperty("user.dir")` and `new File(".")` [usually return the same value](http://docs.oracle.com/javase/7/docs/api/java/io/File.html). So why would this work, while `new File(".")` doesn't, according to the question? – mthmulders Jul 30 '13 at 06:40
0

The File Javadoc says that a relative file is usually resolved against the current user directory. It continues:

This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

So it follows that both new File(".") or System.getProperty("user.dir"); would return the same result. According to the question, you're running from a Windows explorer context menu, which is probably a bit different from a normal JVM invocation.

What you need to do, according to this tutorial, is the following:

  1. Create a new registry key below HKEY_CLASSES_ROOT\Directory\Background\shell. Its name will be used on the Explorer context menu, so let's give it the value MyJavaApp.
  2. Create a new registry key below HKEY_CLASSES_ROOT\Directory\Background\shell\MyJavaApp and name it command. Its value should be the the full path to your Java application. You can add %1 to the command as a placeholder for the currently selected file / directory. This means your program will be invoked with one additional argument.
  3. Your program could read the additional argument to determine which directory it was called from.

Note that the above steps (and tutorial) are for Windows Vista, so you might want to double-check it also works for Windows 8.

mthmulders
  • 9,483
  • 4
  • 37
  • 54