Java Swing實現檔案的簡單讀取
用java Swing實現讀寫檔案的操作
開發平臺:eclipse
安裝WindowsBuilder外掛
參考:https://blog.csdn.net/stormdony/article/details/79497030
新建專案及介面佈局
1.File->new->Project
選擇General->"Project"或者WindowBuilder->SWT Designer->"SWT/JFace Java Project",點選next
2.Ctrl+N 新建類
選擇WindowBuilder->Swing Designer->"Application Window"或"JFrame",點選next
3.頁面佈局
進入設計介面
3.1 使用GroupLayout管理頁面佈局
java Swing窗體有預設佈局,我們需要使用GroupLayout,不受預設佈局的約束,在Palette欄Layouts選框下選擇GroupLayout,拖動到窗體上
3.2 使用JScrollPane控制元件為文字區新增滾動條
Palette欄Containers選框下選擇JScrollPane,拖動到窗體上,改變大小為文字域顯示大小
3.3 選擇JTextArea放入JScrollPane
3.4 選擇JLable,JTextField,JTextArea,JButton等控制元件部署在介面上
JTextFeild和JTextArea的區別:
JTextArea,可以在裡面輸入多行文字
JTextField ,只能在裡面輸入一行文字,也就是單行文字框,JTextField回車會觸發ActionEvent事件
程式碼
雙擊介面按鈕,編寫按鈕點選事件程式碼
定義資料成員:
private File openFile; //檔案類 private FileInputStream fileInputStream; //位元組檔案輸入流 private FileOutputStream fileOutputStream; //位元組檔案輸出流 private OutputStreamWriter outputStreamWriter; //字元檔案輸出流
1.Browse瀏覽系統檔案程式碼:
JButton btnBrowse = new JButton("Browse"); //自動生成
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//自己撰寫
JFileChooser chooser = new JFileChooser(); //檔案選擇
chooser.showOpenDialog(chooser); //開啟檔案選擇窗
openFile = chooser.getSelectedFile(); //獲取選擇的檔案
textPath.setText(openFile.getPath()); //獲取選擇檔案的路徑
}
});
2.read讀取程式碼
JButton btnRead = new JButton("Read"); //系統自動生成
btnRead.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//自己撰寫
openFile = new File(textPath.getText());
try {
if(!openFile.exists()){ //如果檔案不存在
openFile.createNewFile();//建立檔案
}
fileInputStream = new FileInputStream(openFile); //建立檔案輸入流
byte b[] = new byte[(int) openFile.length()]; //定義檔案大小的位元組資料
fileInputStream.read(b); //將檔案資料儲存在b陣列
content = new String(b,"UTF-8"); //將位元組資料轉換為UTF-8編碼的字串
textArea.setText(content); //文字區顯示檔案內容
fileInputStream.close(); //關閉檔案輸入流
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
3.Save儲存檔案
JButton btnSave = new JButton("Save"); //自動生成
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//自己撰寫
openFile = new File(textPath.getText());
try {
fileOutputStream = new FileOutputStream(openFile);
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"utf-8");
content = textArea.getText();
outputStreamWriter.write(content);
outputStreamWriter.flush(); //清空快取
outputStreamWriter.close(); //關閉檔案字元輸出流
fileOutputStream.close(); //關閉檔案位元組輸出流
} catch (Exception e1) {
e1.printStackTrace();
}
}
4.退出系統
在Exit按鈕點選響應事件程式碼里加入:
System.exit(0);