• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

File q, help requested!

 
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ??
 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic