Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the user.dir system property working in Java?

Almost every article I read told me that you can't have chdir in Java. The accepted answer to this question says you can't do it in Java.

However, here's some of the stuff I tried:

geo@codebox:~$ java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing)

Here's a test class I'm using:

import java.io.*;

public class Ch {
    public static void main(String[] args) {
        System.out.println(new File(".").getAbsolutePath());
        System.setProperty("user.dir","/media");
        System.out.println(new File(".").getAbsolutePath());
    }
}
geo@codebox:~$ pwd
/home/geo
geo@codebox:~$ java Ch
/home/geo/.
/media/.

Please explain why this worked. Can I use this from now on and expect it to work the same way on all platforms?

like image 448
Geo Avatar asked Aug 05 '09 18:08

Geo


People also ask

What is system property in Java?

Java™ system properties determine the environment in which a Java program runs by starting a Java virtual machine with a set of values. You can choose to use the default values for Java system properties or you can specify values for them by adding parameters to the command line when you start your application.

How does system getProperty work in Java?

The getProperty(String key) method in Java is used to returns the system property denoted by the specified key passed as its argument.It is a method of the java. lang. System Class. where key is the name of the System property.

How do I set Java system properties in Windows?

System properties are set on the Java command line using the -Dpropertyname=value syntax. They can also be added at runtime using System. setProperty(String key, String value) or via the various System. getProperties().


2 Answers

Just because new File(".") gives the desired answer doesn't mean it's doing what you want it to.

For example, try:

new FileOutputStream("foo.txt").close();

Where does that end up? On my Windows box, even though new File(".").getAbsolutePath() moves around based on user.dir, foo.txt is always created in the original working directory. It strikes me that setting user.dir such that new File(".") doesn't refer to the current working directory is just asking for trouble.

like image 125
Jon Skeet Avatar answered Nov 15 '22 17:11

Jon Skeet


Quote:

The user.dir property is set at VM startup to be the working directory. You should not change this property or set it on the command-line. If you do, then you will see some inconsistent behaviour as there places in the implementation that assumes that the user.dir is the working directory and that it doesn't change during the lifetime of the VM.

The discussion is here

like image 32
01es Avatar answered Nov 15 '22 16:11

01es