Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing Files to The Current Directory

 
Arthur Blair
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By default the classes in the java.io 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
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic