Java Reference
In-Depth Information
add( new JScrollPane(textArea) , BorderLayout.CENTER) ;
...
}
}
Note that, for simplicity, we have removed the code for the control bar that can be used to
change the font style and size. The showDialog method takes as input NotepadFrame.this .
This is the reference to the outer object, that is, the window from which the file dialog
should be displayed. The line textArea.append(line + "
n") simply appends the line
that is read from the file to the text area followed by a new line.
\
When reading and writing to a file, something can always go wrong. For example,
we may try to open a file that does not exist or we do not have permission to access
it. This is why an exception can be generated. Java forces us to always handle this
type of exception because all exceptions that relate to files are checked exceptions.
In the above code, we used a try -with-resources block. If we are unable to open the
file, control jumps over to the catch block. Here, we chose not to do anything in the
catch block. The advantage of using a try -with-resources statement is that we did not
have to close the file. If we used the regular try-catch block, then we had to add the line
fileHandler.close() to the end of the try block or in a new finally block.
13.2.3 Writing to Text Files
Next, let us consider how we can write to a text file. One way to do this is by creating
an object of type PrintWriter . The parameter of the constructor can be either the name
of a file or a file object. After the print writer is created, we can call the same methods we
called on the System.out object to print output. Here is example code that creates a file
and writes two lines to it.
try (PrintWriter fileWritter = new PrintWriter( "myFile.txt" )) {
fileWritter .println( "Hello" );
fileWritter .println( "Do you like Java?" );
}
catch (Exception exception)
{
}
Note that opening a file for writing is similar to opening a file for reading: something
can go wrong. Therefore, Java requires that we always handle a possible exception. In the
above syntax, we do not have to worry about closing the file. Since the file is opened inside
the try parentheses, it will be automatically closed. If we used the regular try - catch block,
then we had to include the statement fileWritter.close() at the end of the try block
or inside a newly introduced finally block.
Below is the new code that needs to be added in order to allow file saving in our Notepad
application.
import java . io . ;
public class NotepadFrame extends JFrame
{
...
JMenuItem saveMenuItem = new JMenuItem( "Save..." );
fileMenu .add(saveMenuItem) ;
saveMenuItem. addActionListener( new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
 
Search WWH ::




Custom Search