aspose file tools*
The moose likes I/O and Streams and the fly likes Why does new File( Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Why does new File("MyFile.txt") in a web-app generate the file in context root?" Watch "Why does new File("MyFile.txt") in a web-app generate the file in context root?" New topic
Author

Why does new File("MyFile.txt") in a web-app generate the file in context root?

Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
I mean my first impression was it should be generated in the current directory.

So if My Context name is MyApp(a J2EE project ..)

and it has this structure (in addition to others):

MyApp/src/main/java/com/utils (src/main/java is in the classpath)

And i have a file creation util class say MyFileCreator.java in the utils folder having

File f = new File("MyFile.txt");

the above code creates the file in MyApp and not in the utils package ... WHY?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41905
    
  63
Web apps do not have a concept of a "current directory", in particular not one tied to the currently executing class. It may be the root of the web app, but that's not specified, so you can't rely on it. That's why you need to use absolute paths in web apps.


Ping & DNS - my free Android networking tools app
Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
Hmm ..

Actually i realized that its eclipse that does that 'Create in context root' thing ..

You are right UD we cannot rely on that ..

Thanks bro
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

For which ServletContext.getRealPath can help you out. For instance, to get a file in the root of the WEB-INF folder:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
Great

Thanks RP
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

You're welcome.
 
Consider Paul's rocket mass heater.
 
subject: Why does new File("MyFile.txt") in a web-app generate the file in context root?