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?
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.
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.
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().
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With