File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Writing Files to The Current Directory Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Writing Files to The Current Directory" Watch "Writing Files to The Current Directory" New topic

Writing Files to The Current Directory

Arthur Blair
Ranch Hand

Joined: Sep 20, 2005
Posts: 71
By default the classes in the package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

Ok. So when I change the current user directory, why do the files still get written to the directory that was being used before I changed it?

I would like to write to C:/ThinkingInJava/src/io/ but this always writes to C:/ThinkingInJava. Am I doing something wrong in the following code?

Compiler output is:

Thoughts appreciated.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

user.dir is set to the Java process' current working directory when Java starts up. You can read the value of this property, but there's no reason to change it. Changing this property doesn't change the current working directory -- there's no way to do that.

To write to a subdirectory of the current directory, you can pass a relative path to the FileOutputStream constructor rather than a plain filename.
[ November 28, 2005: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
The following seems to be working for me, indication that I can change
the defualt directory via that property:

I can't put my finger on it, but I find something smells bad with the
above approach. I would either use absolute paths or better relative paths
to solve your problem.

There is no emoticon for what I am feeling!
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Some classes may indeed use "user.dir" to determine the current directory. This does not mean that all classes will, or that all native libraries will. Changing user.dir does not have defined results.

There are several bugs in Sun's "Bug database" regarding this issue. See, for example, this one and this one. The evaluation of the latter one explicitly says that you shouldn't change user.dir .
Consider Paul's rocket mass heater.
subject: Writing Files to The Current Directory
It's not a secret anymore!