本範例展示如何使用 Java Swing 構建 GUI 介面,結合 RandomAccessFile 與 NIO FileChannel 實現文件的讀取、編輯、保存,並包含文件鎖機制防止併發衝突。
public class SimpleNotepad implements ActionListener {
private Frame frame;
private TextArea ta;
private FileDialog fd_load, fd_save;
private String file = "";
private RandomAccessFile raf;
private FileChannel fci;
private FileLock flock;
private CharsetEncoder encoder;
private CharsetDecoder decoder;
public void init() {
// 1. 構建 UI:Frame, MenuBar, Menu, MenuItem, TextArea
// 2. 註冊事件監聽
// 3. 初始化 FileDialog、Charset 編解碼器
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("打開".equals(cmd)) {
fd_load.setVisible(true);
String dir = fd_load.getDirectory();
String fname = fd_load.getFile();
if (dir != null && fname != null) {
String path = dir + fname;
if (!path.equals(file)) {
closeFile(); // 關閉舊文件
file = path;
loadFile(); // 加載新文件
}
}
} else if ("保存".equals(cmd)) {
saveFile();
}
}
private void loadFile() {
try {
raf = new RandomAccessFile(file, "rw");
fci = raf.getChannel();
flock = fci.tryLock(); // 嘗試獲取獨佔鎖
if (flock == null) {
JOptionPane.showMessageDialog(null, "文件正被佔用,無法獨佔打開!", "錯誤", JOptionPane.ERROR_MESSAGE);
closeFile();
return;
}
// NIO 讀取:ByteBuffer -> CharBuffer -> String
int len = (int) fci.size();
ByteBuffer bb = ByteBuffer.allocate(len);
fci.read(bb);
bb.flip();
CharBuffer cb = decoder.decode(bb);
ta.setText(cb.toString());
frame.setTitle("My Notepad - " + file);
save.setEnabled(true);
} catch (IOException ex) { ex.printStackTrace(); }
}
private void saveFile() {
String content = ta.getText();
try {
CharBuffer cb = CharBuffer.wrap(content.toCharArray());
ByteBuffer bb = encoder.encode(cb);
raf.setLength(0); // 清空文件
fci.write(bb);
fci.force(true); // 強制寫入磁盤
} catch (IOException ex) { ex.printStackTrace(); }
}
private void closeFile() {
try {
if (flock != null) flock.release();
if (raf != null) raf.close();
file = "";
frame.setTitle("My Notepad");
save.setEnabled(false);
} catch (IOException ex) { ex.printStackTrace(); }
}
}
FileChannel.tryLock() 實現進程級獨佔訪問,避免數據衝突。ByteBuffer、CharBuffer、CharsetEncoder/Decoder 高效處理二進制與字符轉換,自動適應編碼。closeFile() 中釋放鎖、關閉通道、重置狀態,防止資源洩漏。try-with-resources (JDK 7+) 自動關閉資源。JTextPane 支持富文本。