Академический Документы
Профессиональный Документы
Культура Документы
SE15: Streams and File I/O 30–5 SE15: Streams and File I/O 30–6
Opening a text file for writing with
PrintWriter FileNotFoundException
First declare a variable of type PrintWriter e.g.. When you open a file for writing the constructor might throw an exception
PrintWriter outputStream = null; FileNotFoundException
It means the file could not be created, such as when the filename was
(this is the name of the stream) already in use for a directory name
You should therefore catch the exception in a catch block or throw it
Next construct the outputStream object by calling the constructor for PrintWriter outputStream = null;
the PrintWriter class try
The PrintWriter class has no constructor that takes a file {
name as its argument so we use the class FileOutputStream to outputStream = new PrintWriter(new
create a stream that can be used as an argument to the FileOutputStream(“out.txt”));
PrintWriter constructor e.g. }
new FileOutputStream(“out.txt”) catch(FileNotFoundException e)
{
outputStream = new PrintWriter( System.out.println(“Error openning file”);
System.exit(0);
new FileOutputStream(“out.txt”));
}
SE15: Streams and File I/O 30–7 SE15: Streams and File I/O 30–8
When readline tries to read beyond the end of the file it returns A typical Windows path name is
null D:\homework1\data.txt
When your program has finished reading from the file, it should
To create a FileReader for this file you use
close the stream connected to the file. new FileReader(“D:\\homework1\\data.txt”);
inputStream.close();
SE15: Streams and File I/O 30–13 SE15: Streams and File I/O 30–14
SE15: Streams and File I/O 30–15 SE15: Streams and File I/O 30–16