小弟刚学JAVA,今天写程序时碰到了一个问题:
代码如下:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class me5 extends JFrame implements ActionListener
{

JPanel P1;
static JTextField T1;
JButton B1;
GridLayout G1;
//static File f1;
static byte b[]=new byte[10];
me5()
{
P1=new JPanel();
T1=new JTextField(10);
B1=new JButton("确认");
G1=new GridLayout (2,1); P1.setLayout(G1);
this.getContentPane().add(P1); P1.add(T1);
P1.add(B1);
B1.addActionListener(this);
this.setSize(300,100);
this.setVisible(true);
}
 
 public static void add()
{
try
{
FileOutputStream OS= new FileOutputStream("a.txt");
String s = T1.getText();
byte b[]=s.getBytes(); OS.write(b,0,10);
OS.close();
}
catch(Exception e)
{
}
}

public static void main(String arg[])
{
new me5();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==B1)
{
add();
JOptionPane.showMessageDialog(null,"OK! ");
}
}}程序一个JTextField 一个JButton 等于只要往JTextField中写入字串.然后点击JButton 程序就会生成一个名为A.TXT的文件,里面记录的就是你输入的字串,但是上面的代码有问题,谁能帮我改正一下啊~~~
先谢谢了~~~

解决方案 »

  1.   


    FileOutputStream OS= new FileOutputStream("a.txt");
    String s = T1.getText();
    byte b[]=s.getBytes(); OS.write(b,0,10);
    OS.close();
    改成
    ---------------------------------------------------------
    FileWriter fw = new FileWriter("a.txt");
    fw.write(T1.getText());
    fw.close();
      

  2.   

    public static void add()
    {
    try
    {
    FileOutputStream OS= new FileOutputStream(new File("a.txt"), true); //以追加模式打开
    String s = T1.getText();
    byte b[]=s.getBytes(); OS.write(b,0,10); -> OS.write(b,0,b.length); 
    OS.close();//最好之前加上OS.flush();
    }
    catch(Exception e)
    {
    }
    }其他没工夫看了
      

  3.   

    public static void add()
    {
    try
    {

    PrintWriter out=new PrintWriter("a.txt");
    String s = T1.getText(); System.out.println(s); if(!s.equals(""))
    {
    out.println(s); }
    out.close();
    }
    catch(Exception e)
    {
    }
    }