App下載

如何使用Java GUI來(lái)實(shí)現(xiàn)文本文件的讀寫(xiě)?詳細(xì)代碼分析!

猿友 2021-07-29 10:50:08 瀏覽數(shù) (2424)
反饋

一、實(shí)驗(yàn)題目

202105230841511

二、分析

實(shí)驗(yàn)要求為:


  • 實(shí)現(xiàn)一個(gè)界面,界面中包含一個(gè)文本顯示區(qū)和兩個(gè)按鈕(存檔和讀檔)
  • 讀檔按鈕作用是打開(kāi)文件并讀取內(nèi)容,將內(nèi)容顯示在文本區(qū)中
  • 存檔按鈕作用是將文本區(qū)的內(nèi)容寫(xiě)入到文件中。

簡(jiǎn)單分析一下,可以看出這樣的要求奧,包含的要考察知識(shí)點(diǎn)主要有兩個(gè)方向:

  • GUI繪制界面并添加事件
  • 使用IO流對(duì)象對(duì)文件進(jìn)行讀寫(xiě)

好的小伙伴們,廢話不多說(shuō),下面就來(lái)的實(shí)現(xiàn)它。

三、實(shí)現(xiàn)

首先,讓我們創(chuàng)建一個(gè)GUI界面,先秉持著一切從簡(jiǎn)的設(shè)計(jì)思想,預(yù)計(jì)它長(zhǎng)這樣:

202105230841512

這樣的布局方式,我們可以選擇采用流布局實(shí)現(xiàn),在容器中直接放入文本顯示區(qū)和兩個(gè)按鈕,適當(dāng)調(diào)整窗口大小即可實(shí)現(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{

	//三個(gè)組件
	private JButton saveButton;
	private JButton loadButton;
	private TextArea textArea;
	
	//容器
	private Container container;
	
	public GUIDemo() {
		//設(shè)置title
		super("File Demo");
		
		//設(shè)置流布局
		setLayout(new FlowLayout());
		
		//獲取容器
		container = getContentPane();
		
		//三個(gè)組件
		textArea = new TextArea();
		saveButton = new JButton("save");
		loadButton = new JButton("load");
		
		//保存文件按鈕點(diǎn)擊事件
		saveButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				System.out.println("存檔成功");
			}
		});
		
		//讀入文件按鈕點(diǎn)擊事件
		loadButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				System.out.println("讀檔成功");
			}
		});
		
		//裝填三個(gè)組件
		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);
	}
}

代碼的含義都在注釋里面,就不啰嗦講解了。

跑起來(lái)是這個(gè)樣子:

202105230841513

點(diǎn)擊兩下按鈕測(cè)試點(diǎn)擊事件,控制臺(tái)輸出:

在這里插入圖片描述

好的,GUI界面設(shè)計(jì)完畢,下面來(lái)為兩個(gè)按鈕編寫(xiě)點(diǎn)擊事件。

首先要解決的一個(gè)問(wèn)題是“目標(biāo)文件”。由于題目中沒(méi)有提到目標(biāo)文件是否需要從文件系統(tǒng)中選取產(chǎn)生,那么我們不妨?xí)簳r(shí)將目標(biāo)文件地址直接在代碼中,令private static final String TARGET_FILE= "./temp.txt";

在這里插入圖片描述

那么在初始化頁(yè)面時(shí)就應(yīng)該先創(chuàng)建這個(gè)文件路徑對(duì)應(yīng)的file對(duì)象:

//目標(biāo)文件
	private File targetFile;
...
//創(chuàng)建目標(biāo)文件對(duì)象
	targetFile = new File(TARGET_FILE);
	if(targetFile.createNewFile()) {
		System.out.println("文件不存在,創(chuàng)建成功");
	}else {
		System.out.println("文件存在");
	}

這里需要注意幾個(gè)問(wèn)題:

1.創(chuàng)建目標(biāo)文件需要使用createNewFile()方法,而非mkdir()方法。否則會(huì)創(chuàng)建成為文件夾而非文件

2.createNewFile()方法會(huì)拋出一個(gè)IOException,為了便于處理,這里直接選擇將異常從構(gòu)造方法和主方法中拋出;

在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

處理好目標(biāo)文件問(wèn)題,兩次啟動(dòng)程序,可以看到控制臺(tái)輸出:

在這里插入圖片描述
在這里插入圖片描述

哦吼,文件處理成功。

接著,就是在為兩個(gè)按鈕添加點(diǎn)擊事件。在下面的處理中,對(duì)于IO流的選擇,我們統(tǒng)一選擇字符流.

首先是讀檔按鈕,它的點(diǎn)擊事件邏輯大致為:

1.創(chuàng)建目標(biāo)文件的輸入字符流

2.從輸入流中讀取文件中的內(nèi)容并形成結(jié)果

3.關(guān)閉輸入流

4.將讀入的結(jié)果顯示在文本顯示區(qū)中

實(shí)現(xiàn)成為代碼:

//讀入文件按鈕點(diǎn)擊事件
loadButton.addActionListener(new ActionListener() {
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		try {
			//字符讀入流
			FileReader reader = new FileReader(targetFile);
			
			//讀入緩沖區(qū)
			char[] buffer = new char[1024];
			
			//讀入結(jié)果
			StringBuffer result = new StringBuffer();
			
			//每次讀入緩沖區(qū)的長(zhǎng)度
			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 block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}
});

在目標(biāo)文件中寫(xiě)下Hello World!!,運(yùn)行程序,點(diǎn)擊load:

2021052308415212

nice~~

好的,接下來(lái)就剩下最后一項(xiàng)任務(wù)了,完成存檔!

存檔按鈕的點(diǎn)擊事件應(yīng)該為:

1.打開(kāi)目標(biāo)文件字符輸出流

2.獲取當(dāng)前文本顯示區(qū)的內(nèi)容

3.將文本顯示區(qū)的內(nèi)容通過(guò)輸出流寫(xiě)入文件

4.關(guān)閉輸出流

5.清空文本顯示區(qū)

哦吼,最后一條是我加上去的,其實(shí)不清空也可以。

代碼實(shí)現(xiàn)如下:

//保存文件按鈕點(diǎn)擊事件
saveButton.addActionListener(new ActionListener() {
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		try {
			//打開(kāi)文件字符輸出流
			FileWriter writer = new FileWriter(targetFile);
		
			//獲取文本顯示區(qū)文本
			String result = textArea.getText();
			
			//寫(xiě)入文件
			writer.write(result);
			
			//關(guān)閉輸出流
			writer.close();
			
			//清空文本顯示區(qū)內(nèi)容
			textArea.setText("");
			
			System.out.println("存檔成功");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
});

在文本顯示區(qū)中輸入Hello Java!!,點(diǎn)擊save:

2021052308415213

啥?你說(shuō)文本框里面啥也沒(méi)有?對(duì),因?yàn)樽詈蟀褍?nèi)容清空了!

四、全部代碼

好了,實(shí)現(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";
	
	//三個(gè)組件
	private JButton saveButton;
	private JButton loadButton;
	private TextArea textArea;
	
	//容器
	private Container container;
	
	//目標(biāo)文件
	private File targetFile;
	
	public GUIDemo() throws IOException {
		//設(shè)置title
		super("File Demo");
		
		//設(shè)置流布局
		setLayout(new FlowLayout());
		
		//獲取容器
		container = getContentPane();
		
		//創(chuàng)建目標(biāo)文件對(duì)象
		targetFile = new File(TARGET_FILE);
		if(targetFile.createNewFile()) {
			System.out.println("文件不存在,創(chuàng)建成功");
		}else {
			System.out.println("文件存在");
		}
		
		//三個(gè)組件
		textArea = new TextArea();
		saveButton = new JButton("save");
		loadButton = new JButton("load");
		
		//保存文件按鈕點(diǎn)擊事件
		saveButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				try {
					//打開(kāi)文件字符輸出流
					FileWriter writer = new FileWriter(targetFile);
				
					//獲取文本顯示區(qū)文本
					String result = textArea.getText();
					
					//寫(xiě)入文件
					writer.write(result);
					
					//關(guān)閉輸出流
					writer.close();
					
					//清空文本顯示區(qū)內(nèi)容
					textArea.setText("");
					
					System.out.println("存檔成功");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		//讀入文件按鈕點(diǎn)擊事件
		loadButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				try {
					//字符讀入流
					FileReader reader = new FileReader(targetFile);
					
					//讀入緩沖區(qū)
					char[] buffer = new char[1024];
					
					//讀入結(jié)果
					StringBuffer result = new StringBuffer();
					
					//每次讀入緩沖區(qū)的長(zhǎng)度
					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 block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				
			}
		});
		
		//裝填三個(gè)組件
		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)于通過(guò) Java 程序編寫(xiě) GUI 來(lái)實(shí)現(xiàn)文本文件的讀寫(xiě)功能的全部?jī)?nèi)容,想要了解更多關(guān)于 Java GUI 的其他內(nèi)容,請(qǐng)關(guān)注W3Cschool相關(guān)技術(shù)文章,也希望大家能夠多多關(guān)注和支持我們!


0 人點(diǎn)贊