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(); } } |
|
来自: 昵称20775372 > 《文件的读与写》