Java Reference
In-Depth Information
and so forth. Display 10.11 gives a sample program that uses the class
File
with text
files. (The class
File
works the same with binary files as it does with text files.)
Note that the
File
class constructor takes a name, known as the
abstract name
, as
an (string) argument. So the
File
class really checks properties of names. For example,
the method
exists
tests whether there is a file with the abstract name. Moreover, the
abstract name may be a potential directory (folder) name. For example, the method
isDirectory
tests whether the abstract name is the name of a directory (folder). The
abstract name may be either a relative path name (which includes the case of a simple
file name) or a full path name.
Display 10.12 lists some of the methods in the class
File
.
abstract name
The
File
Class
The
File
class is like a wrapper class for file names. The constructor for the class
File
takes
a string as an argument and produces an object that can be thought of as the file with that
name. You can use the
File
object and methods of the class
File
to answer questions, such
as: Does the file exist? Does your program have permission to read the file? Does your pro-
gram have permission to write to the file? Display 10.14 has a summary of some of the meth-
ods for the class
File
.
EXAMPLE
File fileObject =
new
File("data.txt");
if
( ! fileObject.canRead())
System.out.println("File data.txt is not readable.");
Display 10.11
Using the
File
Class
(part 1 of 2)
1
import
java.util.Scanner;
2
import
java.io.File;
3
import
java.io.PrintWriter;
4
import
java.io.FileOutputStream;
5
import
java.io.FileNotFoundException;
6
public
class
FileClassDemo
7{
8
public
static
void
main(String[] args)
9
{
10
Scanner keyboard =
new
Scanner(System.in);
11
String line =
null
;
12
String fileName =
null
;
13
System.out.println("I will store a line of text for you.");
14
System.out.println("Enter the line of text:");
15
line = keyboard.nextLine();
(continued)