The file notLikely.txt Does Not exist.
import java.io.*;
class TestExist
{
public static void main ( String[] args )
{
String pathName;
if ( args.length == 1 )
pathName = args[0];
else
pathName = "";
File test = new File( pathName );
if ( test.exists() )
System.out.println( "The file " + pathName + " exists." );
else
System.out.println( "The file " + pathName + " Does Not exist." );
}
}
The File
constructor does not throw IOException
s.
The path name is not checked to see if it exists.
The example program (above) has been changed so that the
file name comes from the command line.
The File
constructor does throw a
NullPointerException
if the argument is null,
but this is an unchecked exception and need not be caught
Try running it with a variety of arguments on the command line, with both file names and directory names. Here are some examples. Some arguments are relative path names, others are absolute pathnames, and some are directory names.
C:\JavaSource>java TestExist TestExist.java The file TestExist.java exists. C:\JavaSource>java TestExist ..\JavaSource The file ..\JavaSource exists. C:\JavaSource>java TestExist C:\Temp The file C:\Temp exists. C:\JavaSource>java TestExist C:\glarch.txt The file C:\glarch.txt Does Not exist.
Is C:\glarch.txt a relative or an absolute path name?