分享

文件的读与写

 昵称20775372 2014-12-03

Happy boy:
老师布置的作业,写的不是很好哦,仅供参考!
求大师指点。

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

class IO extends JFrame implements ActionListener {
JButton button1, button2;
JTextArea text;
JPanel pan1, pan2;

public IO() {
super("TF");
button1 = new JButton("打开文件");
button2 = new JButton("写入文件");
button1.addActionListener(this);//添加事件监听器
button2.addActionListener(this);
text = new JTextArea(15, 30);
text.setBounds(10, 10, 150, 100);
text.setEnabled(true);
JScrollPane scr = new JScrollPane(text,//加入滚动条
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pan1 = new JPanel();
pan2 = new JPanel();
pan1.setLayout(new FlowLayout());
pan1.add(button1);
pan1.add(button2);
// pan2.add(text);
add(pan1, BorderLayout.NORTH);
add(pan2, BorderLayout.CENTER);
pan2.add(scr);
setBounds(200, 300, 400, 400);
setVisible(true);
}

public void write(String str) {//写入文件

File file = new File("d:" + File.separator + "test.txt");
OutputStream out = null;

try {
out = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

byte b[] = str.getBytes();

try {
out.write(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public byte[] read() {//读出文件

File file = new File("d:" + File.separator + "test.txt");
InputStream in = null;

try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

byte b[] = new byte[(int) file.length()];

try {
in.read(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}

@Override
public void actionPerformed(ActionEvent e) {//事件处理函数
// TODO Auto-generated method stub
if (e.getSource() == button1) {
String str2;
str2 = new String(read());
text.setText(str2);
} else if (e.getSource() == button2) {
String str1 = text.getText();
write(str1);
}

}
}

public class IoExperiment {//主类

public static void main(String[] args) {
IO io = new IO();
}

}




    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多