Java Reference
In-Depth Information
Display 10.11
Using the File Class (part 2 of 2)
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
}
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
{
System.out.println("Error opening the file " + fileName);
36
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.
 
Search WWH ::




Custom Search