The File class in Java already creates txt files ???, Javatxt
Private JButton getOpenButton (){
If (openButton = null ){
OpenButton = new JButton ();
OpenButton. setText ("Write File"); // prompt message for modifying the button
OpenButton. addActionListener (new java. awt. event. ActionListener (){
// Button click event
Public void actionreceivmed (ActionEvent e ){
// Create a file object
File file = new File ("word.txt ");
Try {
// Create a FileWriter object
FileWriter out = new FileWriter (file );
// Obtain the text in the text field
String s = jTextArea. getText ();
Out. write (s); // write information to the disk file.
Out. close (); // close the stream
} Catch (Exception e1 ){
E1.printStackTrace ();
}
}
});
}
Return openButton;
}
Private JButton getCloseButton (){
If (closeButton = null ){
CloseButton = new JButton ();
CloseButton. setText ("Read File"); // The prompt message for modifying the button
CloseButton. addActionListener (new java. awt. event. ActionListener (){
// Button click event
Public void actionreceivmed (ActionEvent e ){
File file = new File ("word.txt"); // create a File object
Try {
// Create a FileReader object
FileReader in = new FileReader (file );
Char byt [] = new char [1024]; // create a char array
Int len = in. read (byt); // read bytes into the Array
// Set the display information of text fields
JTextArea. setText (new String (byt, 0, len ));
In. close (); // close the stream
} Catch (Exception e1 ){
E1.printStackTrace ();
}
}
});
}
Return closeButton;
}
Starting from the beginning, I thought that the woed.txt file was re-created for both buttons. Isn't it overwritten?
If a file is not created on the hosts file, the word.txt file Created by the fileclass is not actually created. To create a file, use the file. creatNewfile (). In fact, both are new File ("word.txt"), but the cache is temporarily created on the disk.
And because the first key has been created, the second key will be used directly (with the same name ).