Java Reference
In-Depth Information
Display 10.11
Using the File Class (part 2 of 2)
If you wish, you can use fileObject
instead of fileName as the argument to
FileOutputStream .
28 PrintWriter outputStream = null ;
29 try
30 {
31 outputStream =
32
new PrintWriter( new FileOutputStream(fileName));
33 }
34 catch (FileNotFoundException e)
35 {
36 System.out.println("Error opening the file " + fileName);
37 System.exit(0);
38 }
39 System.out.println("Writing \"" + line + "\"");
40 System.out.println("to the file" + fileName);
41 outputStream.println(line);
42 outputStream.close();
43 System.out.println("Writing completed.");
44 }
45 }
The dialogue assumes that there already is a file named
myLine.txt but that there is no file named mySaying.txt .
Sample Dialogue
I will store a line of text for you.
Enter the line of text:
May the hair on your toes grow long and curly.
Enter a file name to hold the line:
myLine.txt
There already is a file named myLine.txt
Enter a different file name:
mySaying.txt
Writing "May the hair on your toes grow long and curly."
to the file mySaying.txt
Writing completed.
Display 10.12
Some Methods in the Class File (part 1 of 3)
File is in the java.io package.
public File(String File_Name )
A constructor. File_Name can be either a full or a relative path name (which includes the case of a
simple file name). File_Name is referred to as the abstract path name .
public boolean exists()
Tests whether there is a file with the abstract path name.
(continued)
 
 
Search WWH ::




Custom Search