黑马程序员_打开文件 保存文件 菜单栏 打开之后显示到textArea 并能将taxtarea保存到文件中

来源:互联网 发布:淘宝卖家最高等级 编辑:程序博客网 时间:2024/06/10 12:04

---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class practice27 
{
private Frame f;
private File fe;
private MenuBar mb;
private Menu m;
private MenuItem mload,msave,mclose;
private TextArea ta;
practice27()
{
ini();
}
public void ini()
{
f=new Frame();
ta=new TextArea();
mb=new MenuBar();
m=new Menu("文件");
mload=new MenuItem("打开");
msave=new MenuItem("保存");
mclose=new MenuItem("关闭");
f.setBounds(200,100,500,400);
f.setLayout(new FlowLayout());
f.add(ta);
f.setMenuBar(mb);
mb.add(m);
m.add(mload);
m.add(msave);
m.add(mclose);
method();
f.setVisible(true);
}
public void method()
{
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}});
mclose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
mload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
FileDialog fdg=new FileDialog(f,"",FileDialog.LOAD);
fdg.setVisible(true);
String dirpath=fdg.getDirectory();
String filepath=fdg.getFile();

if(dirpath==null||filepath==null)
return;
ta.setText("");
fe=new File(dirpath+filepath);
String line;
BufferedReader bis=new BufferedReader(new InputStreamReader(new FileInputStream(fe)));
while((line=bis.readLine())!=null)
{
//String sb=new String(b,0,len);
ta.append(line+"\r\n");
System.out.println(ta.getText());
}
}
catch (Exception ex)
{
throw new RuntimeException("。。。。");
}

}



}
);
msave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try
{
String textstr=ta.getText();
if(fe==null)
{
FileDialog fdg=new FileDialog(f,"",FileDialog.SAVE);
fdg.setVisible(true);
String dirpath=fdg.getDirectory();
String filepath=fdg.getFile();
if(dirpath==null||filepath==null)
return;
else{
fe=new File(dirpath,filepath);}}
PrintStream ps=new PrintStream(new FileOutputStream(fe),true);
ps.println(textstr);
}
catch (Exception ex)
{
throw new RuntimeException(";;;;");
}
}
});


}
public static void main(String[] args) 
{
new practice27();
}
}

---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------

原创粉丝点击