0

As a example:

public class Hello {
    public static void main(String[] args) {
        try {
            OutputStream os = new FileOutputStream(new File("c.txt"));
            try {
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Why was c.txt generated in the root path of current project other then the same path of the java file? enter image description here

thanks.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
liam xu
  • 2,892
  • 10
  • 42
  • 65
  • The [Current Working Directory](http://en.wikipedia.org/wiki/Working_directory) has *nothing* inherently to do with where the Java Source/Class file is located. –  Oct 26 '12 at 05:53

3 Answers3

6

Because the root of your project is your current working directory when starting the JVM. You can check the user.dir system property to see what is your current working directory. If you access a file without a leading slash (Unix) or drive specifier/backslash (Windows), the files will be created relative to your current working directory.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • when I manually set the user.dir using System.setProperty("user.dir","c:\\xuhang"); Why wasn't the file generated in directory c:\\xuhang? Maybe I am wrong to test in this way. – liam xu Oct 26 '12 at 07:20
  • You can not [change the current working directory on java](http://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java) by setting `user.dir`. – Andreas Fester Oct 26 '12 at 07:30
1

You haven't provided a full path - this means that File constructor will use your process's current directory.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
mik1
  • 568
  • 4
  • 7
0

The path you provided will point to the project directory only if you want to change you can also you can mention the full path where file is to be generated.

OutputStream os = new FileOutputStream(new File("c.txt"));

OutputStream os = new FileOutputStream(new File("D:\\c.txt"));
sunleo
  • 10,589
  • 35
  • 116
  • 196