JavaSa
JavaSa

Reputation: 6242

How to change default directory for creating new files

I was using the following c'tor in my java web application

public File(String pathname)  

For example:
File =new File("1.txt");
Then I get the following file in the path:

C:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.22\bin\1.txt  

My question: why is this the default folder when using the above c'tor and also if there is any option to change it by default for the project folder for example.

Thanks

Upvotes: 1

Views: 6433

Answers (3)

rickz
rickz

Reputation: 4474

and also if there is any option to change it by default for the project folder for example.

In a servlet, you can use

File f = new File(getServletContext().getRealPath("/1.txt"));  

Upvotes: 1

Lucifer
Lucifer

Reputation: 29670

As you haven't given a path while creation of file, by default it is creating the file where your .Java file is resides. To prevent this, you can use,

File file = new File ( "C:\\1.txt" );

Now it is going to create 1.txt in C: drive.

You can check the File Documentation. There is no way to set default path instead you specify in in the File() constructor it self.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109613

File for a relative path uses System.getProperty("user.dir"), the application startup directory (which almost always is a bad idea). In a web application you want to use the Servlet's getRealPath("/1.txt") which goes relative from the web app directory. Note not \\ but /.

Upvotes: 1

Related Questions