java实现文件打开与保存
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
安庆师范学院
1.j ava实现文件打开保存。
2.主类我命名为 xititen。
3.实验截图。
4.
4.实验源代码。
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class xititen extends JFrame {
JMenuBar jb = new JMenuBar();
JMenu jm1 = new JMenu("文件"),
jm2 = new JMenu("帮助");
JLabel jl = new JLabel();
JMenuItem jt1,jt2,jt3,jt4,jt5,jt6;
JTextArea ja = new JTextArea();
JScrollPane jp = new JScrollPane(ja);
JFileChooser ch = new JFileChooser();
public xititen(){
setTitle("java 记事本");
ja.setLineWrap(true);
setJMenuBar(jb);
jb.add(jm1);
jb.add(jm2);
jm1.add(jt1 = new JMenuItem("打开"));
jm1.add(jt2 = new JMenuItem("保存"));
jm1.addSeparator();
jm1.add(jt3 = new JMenuItem("退出"));
jm2.add(jt4 = new JMenuItem("关于"));
add(jp,BorderLayout.CENTER);
add(jl,BorderLayout.SOUTH);
jt1.addActionListener(new ML());
jt2.addActionListener(new ML());
jt3.addActionListener(new ML());
jt4.addActionListener(new ML());
setSize(500,400);
setVisible(true);
setLocation(300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
}
class ML implements ActionListener{
public void actionPerformed(ActionEvent e){ String com = e.getActionCommand();
if(com.equals("打开")){
open();
}
else if(com.equals("保存")){
save();
}
else if(com.equals("退出")){
System.exit(0);
}
else if(com.equals("关于")){
JOptionPane.showMessageDialog(xititen.this,"安师院 : 杨成",
" java 记事本
",RMATION_MESSAGE);
}
}
}
public void open(){
if(ch.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
File file = ch.getSelectedFile();
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[in.available()];
in.read(b,0,b.length);
ja.append(new String(b,0,b.length));
in.close();
jl.setText(file.getName() + "已经被打开");
}catch(IOException e){
jl.setText("打开错误" + file.getName());
}
}
}
public void save(){
if(ch.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
File file = ch.getSelectedFile();
try{
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] b = (ja.getText()).getBytes();
out.write(b,0,b.length);
out.close();
jl.setText(file.getName() + "已经被保存");
}catch(IOException e){
jl.setText("保存错误" + file.getName());
}
}
}
public static void main(String[] args){ try{
UIManager.setLookAndFeel(UIManager.getSystemLo okAndFeelClassName());
}catch(Exception e){}
xititen frame = new xititen();
}
}。