2015年12月2日 星期三

【JAVA】 在button事件下的IOException寫法

最近在弄專題
需要利用button來進行置換txt檔案的動作
(配合前篇 - [JAVA]將txt檔中特定字串取代成另一字串
卻發現在actionPerformed下不能throws IOException
必須利用try跟catch來寫

以下是範例
JButton clean = new JButton("BUTTON1");
clean.setBackground(Color.GREEN);
clean.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

try{

String path = "路徑";
FileReader fr= new FileReader(path);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
FileWriter fw = null;
String newContent = "";
String line;

while((line = br.readLine()) != null){
newContent = newContent+line.replace("尋找字串","取代字串")+"\r\n";
}

fw = new FileWriter(path);
fw.write(newContent);
fr.close();
br.close();
fw.close();
}

catch(IOException o){}
}
});