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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 39530
    
  27
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 - updated with new look and Ping home screen widget
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: 19538
    
  16

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: 19538
    
  16

You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does new File("MyFile.txt") in a web-app generate the file in context root?
 
Similar Threads
Reading from a file
Cannot find file location
Basic build.xml file required
How to create File object for servlet and so where to place the folder
Reading a text file from assets folders