Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes File constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "File constructor" Watch "File constructor" New topic
Author

File constructor

siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
File directory = new File(�d�);
File file = new File(directory,�f�);
Can you explain this statements.
Thanks.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

Lets take an example. Suppose your program is in the directory

/home/siddharth/java

then

File directory = new File("d");

here directory will point to the path

/home/siddharth/java/d

this d can be a file or directory. Now the second statement

File file = new File(directory,"f");

Now this object named file will point to the path

/home/siddharth/java/d/f

so basically if you provide two parameters to the file constructor, then the first parameter points to the directory inside which the second parameter will point to...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
if I write the following statement
File file = new File(directory,"h.txt");
instead of
File file = new File(directory,"f");

then what will happen?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

then file = new File(directory,"h.txt"); will point to h.txt inside the directory pointed by directory object...
siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
But I do not find any text file is created.
Narendra shah
Ranch Hand

Joined: Feb 28, 2007
Posts: 51
Hey Dear,

You need to add following statement also as such new File will not create physical file for you.

file.createNewFile() if this is true then your file is created else not.


Narendra Shah -- SCJP 5
siddharth das
Ranch Hand

Joined: Aug 17, 2007
Posts: 124
public static void main(String[] args) {
File p = new File("a");
File f = new File(p,"h.txt");
System.out.println(f.getAbsolutePath());

try

{
f.createNewFile();
}
catch(Exception e){System.out.println("test");}



}

In this case,there is no text file is created.But exception is thrown.
Output is test
Fabian Angy
Ranch Hand

Joined: Oct 27, 2008
Posts: 90
Does your directory "a" exist before the creation of the file?


SCJP 5
Pranav Patel
Greenhorn

Joined: Dec 11, 2008
Posts: 6
You need to create dir.

File p = new File("a");
p.mkdir();
File f = new File(p,"h.txt");
System.out.println(f.getAbsolutePath());

try

{
f.createNewFile();
}
catch(Exception e){System.out.println("test");}



}
 
GeeCON Prague 2014
 
subject: File constructor