• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File q, help requested!

 
sarim raza
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;
class Path {
public static void main(String[] args) throws Exception {
File file = new File("Ran.test");
System.out.println(file.getAbsolutePath());
}
}
What do you expect the output to be? Select the one right answer.
A) Ran.test
B) source\Ran.test
C) c:\source\Ran.test
D) c:\source
E) null
// I CHOSE A, BUT THE CORRECT ANSWER IS C, HOW CAN THIS BE SO WHEN A FILE DOES
NOT CREATE A FILE IN THE CURRENT WORKING DIRECTORY ??
 
Suresh Selvaraj
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The correct answer is C i.e, "c:\source\Ran.test".
The java.io.File class is an abstract representation of File and pathnames. Hence you get the absolute path "c:\source\Ran.test".
Basically this path will be the one where JVM is located.
i.e,"c:\jdk1.3\bin\Ran.test"
The statement " File f1= new File("Ran.test") " just creates an instance of a file "Ran.test" and does not create a physical file in the local hard disk.
For example, you can check for the existence of this file using
f1.exists().
import java.io.*;
class path
{
public static void main(String[] args) throws Exception
{
File file = new File("Ran.test");
System.out.println(file.getAbsolutePath());
if (file.exists())
System.out.println(file);
else
System.out.println("File does not exist");
}
}
The output of this code is "File does not exist".
If the file "Ran.test" is created using FileOutputStream and then checked with exists(), then you will get the answer you expected.
Here is the code,
import java.io.*;
class path
{
public static void main(String[] args) throws Exception
{
File file = new File("Ran.test");
System.out.println(file.getAbsolutePath());
if (file.exists())
System.out.println(file);
else
System.out.println("File does not exist");

FileOutputStream fos= new FileOutputStream("Ran.test");
if (file.exists())
System.out.println("File " + file + " exists");
else
System.out.println("File does not exist");
}
}
- Suresh Selvaraj
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic