文件保存内容为空
代码如下:
package NotePad;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NotePad extends JFrame implements ActionListener{
public void actionPerformed(ActionEvent e) {
// 判断哪个菜单被按下
if(e.getActionCommand().equals("open"))
{
//隆重推荐JFileChooser
JFileChooser jfc1=new JFileChooser();
jfc1.setDialogTitle("请选择文件...");
jfc1.showOpenDialog(null);
jfc1.setVisible(true);
//知道用户选择哪一个文件(绝对路径)
String filename=jfc1.getSelectedFile().getAbsolutePath();
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(filename);
br=new BufferedReader(fr);
//从文件中读取信息并显示到jta
String s="";
String allcon="";
while((s=br.readLine())!=null)
{
allcon+=s+"\r\n";
}
jta.setText(allcon);
} catch (Exception arg) {
arg.printStackTrace();// TODO: handle exception
}finally{
try {
br.close();
fr.close();
} catch (
IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
if(e.getActionCommand().equals("save"))
{
JFileChooser jfc2=new JFileChooser();
jfc2.setDialogTitle("另存为...");
jfc2.showSaveDialog(null);
jfc2.setVisible(true);
//得到用户希望保存的路径
String filename2=jfc2.getSelectedFile().getAbsolutePath();
System.out.println(filename2);
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw=new FileWriter(filename2);
bw=new BufferedWriter(fw);
bw.write(this.jta.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
try {
fw.close();
bw.close();
} catch (Exception e1) {
// TODO: handle exception
}
}
}
}
//定义需要的SWING组件
JTextArea jta=null;
JMenuBar jmb=null;
JMenu jm1=null;
JMenuItem jmi1=null;
JMenuItem jmi2=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
NotePad notepad=new NotePad();
//菜单条
}
public NotePad()
{
jta=new JTextArea();
jmb=new JMenuBar();
jm1=new JMenu("文件");
//设置助记符
jm1.setMnemonic('F');
//jmi1=new JMenuItem("打开",new ImageIcon("/caocao.jpg"));
jmi1=new JMenuItem("打开");
//注册监听
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2=new JMenuItem("保存");
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
//加入
this.setJMenuBar(jmb);
//把jm1放入到jmb
jmb.add(jm1);
//把item放入Menu
jm1.add(jmi1);
jm1.add(jmi2);
this.add(jta);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,300);
this.setVisible(true);
}