Java Reference
In-Depth Information
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 the following: Does the file exist? Does your program have permission
to read the file? Does your program have permission to write to the file? Display 10.14 has a
summary of some of the methods 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();
16 System.out.println("Enter a file name to hold the line:");
17 fileName = keyboard.nextLine();
18 File fileObject =
new
File(fileName);
19
20
while
(fileObject.exists())
21 {
22 System.out.println("There already is a file named "
23 + fileName);
24 System.out.println("Enter a different file name:");
25 fileName = keyboard.nextLine();
26 fileObject =
new
File(fileName);
27 }