教你用Java GUI實現文本文件的讀寫
實驗要求為:
實現一個界面,界面中包含一個文本顯示區和兩個按鈕(存檔和讀檔) 讀檔按鈕作用是打開文件并讀取內容,將內容顯示在文本區中 存檔按鈕作用是將文本區的內容寫入到文件中。簡單分析一下,可以看出這樣的要求奧,包含的要考察知識點主要有兩個方向:
GUI繪制界面并添加事件 使用IO流對象對文件進行讀寫好的小伙伴們,廢話不多說,下面就來的實現它。
三、實現首先,讓我們創建一個GUI界面,先秉持著一切從簡的設計思想,預計它長這樣:
這樣的布局方式,我們可以選擇采用流布局實現,在容器中直接放入文本顯示區和兩個按鈕,適當調整窗口大小即可實現:
import java.awt.Container;import java.awt.FlowLayout;import java.awt.TextArea;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;public class GUIDemo extends JFrame{//三個組件private JButton saveButton;private JButton loadButton;private TextArea textArea;//容器private Container container;public GUIDemo() {//設置titlesuper('File Demo');//設置流布局setLayout(new FlowLayout());//獲取容器container = getContentPane();//三個組件textArea = new TextArea();saveButton = new JButton('save');loadButton = new JButton('load');//保存文件按鈕點擊事件saveButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println('存檔成功');}});//讀入文件按鈕點擊事件loadButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.out.println('讀檔成功');}});//裝填三個組件container.add(textArea);container.add(loadButton);container.add(saveButton);//調整大小setSize(500, 300);//顯示setVisible(true);}public static void main(String[] args) {GUIDemo demo = new GUIDemo();demo.setDefaultCloseOperation(EXIT_ON_CLOSE);}}
代碼的含義都在注釋里面,就不??陸步飭恕?/p>
跑起來是這個樣子:
點擊兩下按鈕測試點擊事件,控制臺輸出:
好的,GUI界面設計完畢,下面來為兩個按鈕編寫點擊事件。
首先要解決的一個問題是“目標文件”。由于題目中沒有提到目標文件是否需要從文件系統中選取產生,那么我們不妨暫時將目標文件地址直接在代碼中,令private static final String TARGET_FILE= './temp.txt';
那么在初始化頁面時就應該先創建這個文件路徑對應的file對象:
//目標文件private File targetFile;...//創建目標文件對象targetFile = new File(TARGET_FILE);if(targetFile.createNewFile()) {System.out.println('文件不存在,創建成功');}else {System.out.println('文件存在');}
這里需要注意幾個問題:
1.創建目標文件需要使用createNewFile()方法,而非mkdir()方法。否則會創建成為文件夾而非文件
2.createNewFile()方法會拋出一個IOException,為了便于處理,這里直接選擇將異常從構造方法和主方法中拋出;
處理好目標文件問題,兩次啟動程序,可以看到控制臺輸出:
哦吼,文件處理成功。
接著,就是在為兩個按鈕添加點擊事件。在下面的處理中,對于IO流的選擇,我們統一選擇字符流.
首先是讀檔按鈕,它的點擊事件邏輯大致為:
1.創建目標文件的輸入字符流
2.從輸入流中讀取文件中的內容并形成結果
3.關閉輸入流
4.將讀入的結果顯示在文本顯示區中
實現成為代碼:
//讀入文件按鈕點擊事件loadButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//字符讀入流FileReader reader = new FileReader(targetFile);//讀入緩沖區char[] buffer = new char[1024];//讀入結果StringBuffer result = new StringBuffer();//每次讀入緩沖區的長度int len;//從讀入流中讀取文件內容并形成結果while((len = reader.read(buffer)) != -1) {result.append(buffer,0,len);}//關閉讀入流reader.close();//更新文本顯示區內容textArea.setText(result.toString());System.out.println('讀檔成功');} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});
在目標文件中寫下Hello World!!,運行程序,點擊load:
nice~~
好的,接下來就剩下最后一項任務了,完成存檔!
存檔按鈕的點擊事件應該為:
1.打開目標文件字符輸出流
2.獲取當前文本顯示區的內容
3.將文本顯示區的內容通過輸出流寫入文件
4.關閉輸出流
5.清空文本顯示區
哦吼,最后一條是我加上去的,其實不清空也可以。
代碼實現如下:
//保存文件按鈕點擊事件saveButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//打開文件字符輸出流FileWriter writer = new FileWriter(targetFile);//獲取文本顯示區文本String result = textArea.getText();//寫入文件writer.write(result);//關閉輸出流writer.close();//清空文本顯示區內容textArea.setText('');System.out.println('存檔成功');} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});
在文本顯示區中輸入Hello Java!!,點擊save:
啥?你說文本框里面啥也沒有?對,因為最后把內容清空了!
四、全部代碼好了,實現了上面的全部功能,最后把代碼匯總在這里:
(謹慎抄襲哦)
import java.awt.Container;import java.awt.FlowLayout;import java.awt.TextArea;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import javax.swing.JButton;import javax.swing.JFrame;public class GUIDemo extends JFrame{private static final String TARGET_FILE = './temp.txt';//三個組件private JButton saveButton;private JButton loadButton;private TextArea textArea;//容器private Container container;//目標文件private File targetFile;public GUIDemo() throws IOException {//設置titlesuper('File Demo');//設置流布局setLayout(new FlowLayout());//獲取容器container = getContentPane();//創建目標文件對象targetFile = new File(TARGET_FILE);if(targetFile.createNewFile()) {System.out.println('文件不存在,創建成功');}else {System.out.println('文件存在');}//三個組件textArea = new TextArea();saveButton = new JButton('save');loadButton = new JButton('load');//保存文件按鈕點擊事件saveButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//打開文件字符輸出流FileWriter writer = new FileWriter(targetFile);//獲取文本顯示區文本String result = textArea.getText();//寫入文件writer.write(result);//關閉輸出流writer.close();//清空文本顯示區內容textArea.setText('');System.out.println('存檔成功');} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});//讀入文件按鈕點擊事件loadButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//字符讀入流FileReader reader = new FileReader(targetFile);//讀入緩沖區char[] buffer = new char[1024];//讀入結果StringBuffer result = new StringBuffer();//每次讀入緩沖區的長度int len;//從讀入流中讀取文件內容并形成結果while((len = reader.read(buffer)) != -1) {result.append(buffer,0,len);}//關閉讀入流reader.close();//更新文本顯示區內容textArea.setText(result.toString());System.out.println('讀檔成功');} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});//裝填三個組件container.add(textArea);container.add(loadButton);container.add(saveButton);//調整大小setSize(500, 300);//顯示setVisible(true);}public static void main(String[] args) throws IOException {GUIDemo demo = new GUIDemo();demo.setDefaultCloseOperation(EXIT_ON_CLOSE);}}
相關文章:
