教你用Java GUI實現(xiàn)文本文件的讀寫
實驗要求為:
實現(xiàn)一個界面,界面中包含一個文本顯示區(qū)和兩個按鈕(存檔和讀檔) 讀檔按鈕作用是打開文件并讀取內(nèi)容,將內(nèi)容顯示在文本區(qū)中 存檔按鈕作用是將文本區(qū)的內(nèi)容寫入到文件中。簡單分析一下,可以看出這樣的要求奧,包含的要考察知識點主要有兩個方向:
GUI繪制界面并添加事件 使用IO流對象對文件進(jìn)行讀寫好的小伙伴們,廢話不多說,下面就來的實現(xiàn)它。
三、實現(xiàn)首先,讓我們創(chuàng)建一個GUI界面,先秉持著一切從簡的設(shè)計思想,預(yù)計它長這樣:
這樣的布局方式,我們可以選擇采用流布局實現(xiàn),在容器中直接放入文本顯示區(qū)和兩個按鈕,適當(dāng)調(diào)整窗口大小即可實現(xiàn):
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() {//設(shè)置titlesuper('File Demo');//設(shè)置流布局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);//調(diào)整大小setSize(500, 300);//顯示setVisible(true);}public static void main(String[] args) {GUIDemo demo = new GUIDemo();demo.setDefaultCloseOperation(EXIT_ON_CLOSE);}}
代碼的含義都在注釋里面,就不??陸步飭恕?/p>
跑起來是這個樣子:
點擊兩下按鈕測試點擊事件,控制臺輸出:
好的,GUI界面設(shè)計完畢,下面來為兩個按鈕編寫點擊事件。
首先要解決的一個問題是“目標(biāo)文件”。由于題目中沒有提到目標(biāo)文件是否需要從文件系統(tǒng)中選取產(chǎn)生,那么我們不妨?xí)簳r將目標(biāo)文件地址直接在代碼中,令private static final String TARGET_FILE= './temp.txt';
那么在初始化頁面時就應(yīng)該先創(chuàng)建這個文件路徑對應(yīng)的file對象:
//目標(biāo)文件private File targetFile;...//創(chuàng)建目標(biāo)文件對象targetFile = new File(TARGET_FILE);if(targetFile.createNewFile()) {System.out.println('文件不存在,創(chuàng)建成功');}else {System.out.println('文件存在');}
這里需要注意幾個問題:
1.創(chuàng)建目標(biāo)文件需要使用createNewFile()方法,而非mkdir()方法。否則會創(chuàng)建成為文件夾而非文件
2.createNewFile()方法會拋出一個IOException,為了便于處理,這里直接選擇將異常從構(gòu)造方法和主方法中拋出;
處理好目標(biāo)文件問題,兩次啟動程序,可以看到控制臺輸出:
哦吼,文件處理成功。
接著,就是在為兩個按鈕添加點擊事件。在下面的處理中,對于IO流的選擇,我們統(tǒng)一選擇字符流.
首先是讀檔按鈕,它的點擊事件邏輯大致為:
1.創(chuàng)建目標(biāo)文件的輸入字符流
2.從輸入流中讀取文件中的內(nèi)容并形成結(jié)果
3.關(guān)閉輸入流
4.將讀入的結(jié)果顯示在文本顯示區(qū)中
實現(xiàn)成為代碼:
//讀入文件按鈕點擊事件loadButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//字符讀入流FileReader reader = new FileReader(targetFile);//讀入緩沖區(qū)char[] buffer = new char[1024];//讀入結(jié)果StringBuffer result = new StringBuffer();//每次讀入緩沖區(qū)的長度int len;//從讀入流中讀取文件內(nèi)容并形成結(jié)果while((len = reader.read(buffer)) != -1) {result.append(buffer,0,len);}//關(guān)閉讀入流reader.close();//更新文本顯示區(qū)內(nèi)容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();}}});
在目標(biāo)文件中寫下Hello World!!,運行程序,點擊load:
nice~~
好的,接下來就剩下最后一項任務(wù)了,完成存檔!
存檔按鈕的點擊事件應(yīng)該為:
1.打開目標(biāo)文件字符輸出流
2.獲取當(dāng)前文本顯示區(qū)的內(nèi)容
3.將文本顯示區(qū)的內(nèi)容通過輸出流寫入文件
4.關(guān)閉輸出流
5.清空文本顯示區(qū)
哦吼,最后一條是我加上去的,其實不清空也可以。
代碼實現(xiàn)如下:
//保存文件按鈕點擊事件saveButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {//打開文件字符輸出流FileWriter writer = new FileWriter(targetFile);//獲取文本顯示區(qū)文本String result = textArea.getText();//寫入文件writer.write(result);//關(guān)閉輸出流writer.close();//清空文本顯示區(qū)內(nèi)容textArea.setText('');System.out.println('存檔成功');} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});
在文本顯示區(qū)中輸入Hello Java!!,點擊save:
啥?你說文本框里面啥也沒有?對,因為最后把內(nèi)容清空了!
四、全部代碼好了,實現(xiàn)了上面的全部功能,最后把代碼匯總在這里:
(謹(jǐn)慎抄襲哦)
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;//目標(biāo)文件private File targetFile;public GUIDemo() throws IOException {//設(shè)置titlesuper('File Demo');//設(shè)置流布局setLayout(new FlowLayout());//獲取容器container = getContentPane();//創(chuàng)建目標(biāo)文件對象targetFile = new File(TARGET_FILE);if(targetFile.createNewFile()) {System.out.println('文件不存在,創(chuàng)建成功');}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);//獲取文本顯示區(qū)文本String result = textArea.getText();//寫入文件writer.write(result);//關(guān)閉輸出流writer.close();//清空文本顯示區(qū)內(nèi)容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);//讀入緩沖區(qū)char[] buffer = new char[1024];//讀入結(jié)果StringBuffer result = new StringBuffer();//每次讀入緩沖區(qū)的長度int len;//從讀入流中讀取文件內(nèi)容并形成結(jié)果while((len = reader.read(buffer)) != -1) {result.append(buffer,0,len);}//關(guān)閉讀入流reader.close();//更新文本顯示區(qū)內(nèi)容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);//調(diào)整大小setSize(500, 300);//顯示setVisible(true);}public static void main(String[] args) throws IOException {GUIDemo demo = new GUIDemo();demo.setDefaultCloseOperation(EXIT_ON_CLOSE);}}
相關(guān)文章:
1. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達(dá)式2. 關(guān)于Ajax跨域問題及解決方案詳析3. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進(jìn))4. 刪除docker里建立容器的操作方法5. JavaScript實現(xiàn)組件化和模塊化方法詳解6. .Net Core和RabbitMQ限制循環(huán)消費的方法7. ASP.NET MVC遍歷驗證ModelState的錯誤信息8. SpringMVC+Jquery實現(xiàn)Ajax功能9. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲10. ASP中if語句、select 、while循環(huán)的使用方法
