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();

}

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值