当前位置:文档之家› java-文件打开-保存-新建-另存为

java-文件打开-保存-新建-另存为

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class FileSave extends JFrame implements ActionListener{
JButton b1=new JButton("打开");
JButton b2=new JButton("保存");
JButton b3=new JButton("新建");
JButton b4=new JButton("另存为");
TextArea t=new TextArea();
FileDialog fd=new FileDialog(this,"打开文件",FileDialog.LOAD);

public void init(){
add(b1);add(b2);add(b3);add(b4);add(t);
setVisible(true);
setSize(500,600);
setLayout(null);
b1.setBounds(50,450,50,50);
b2.setBounds(150,450,50,50);
b3.setBounds(250,450,50,50);
b4.setBounds(350,450,50,50);
t.setBounds(50,50,400,300);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){ //打开文件
fd.setVisible(true);
try{
File f=new File(fd.getDirectory(),fd.getFile());
FileInputStream fis=new FileInputStream(f);
byte buf[]=new byte[30000];
int len=fis.read(buf);
t.setText(new String(buf,0,len));
fis.close();
}catch(Exception ecp){}
}
if(e.getSource()==b2){ //保存文件
try{
File f=new File(fd.getDirectory(),fd.getFile());
FileOutputStream fos=new FileOutputStream(f);
fos.write(t.getText().getBytes());
fos.close();
}catch(Exception ecp){}
}
if(e.getSource()==b3){ //新建文件
fd=new FileDialog(this,"新建文件",FileDialog.SAVE);
fd.setVisible(true);
try{
File f=new File(fd.getDirectory(),fd.getFile());
FileOutputStream fos=new FileOutputStream(f);
fos.write("".getBytes());
fos.close();
}catch(Exception ecp){}
}
if(e.getSource()==b4){ //另存为
fd=new FileDialog(this,"文件另存为",FileDialog.SAVE);
fd.setVisible(true);
try{
File f=new File(fd.getDirectory(),fd.getFile());
FileOutputStream fos=new FileOutputStream(f);
fos.write(t.getText().getBytes());
fos.close();
}catch(Exception ecp){}
}
}

public static void main(String [] args){
FileSave fs=new FileSave();
fs.init();
}
}


相关主题
文本预览
相关文档 最新文档