自己写了段代码有关打开和保存一个文件的问题,编译成功,运行问题也不大!但是出现了个问题是,程序只能读取文件的一部份!请高手帮忙改下,代码如下!import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class testrw2 extends WindowAdapter implements ActionListener{ Frame f;
Button o,b;
String name;
TextArea ta;
public static void main(String[] args)
{ new testrw2(args[0]);}
public testrw2(String name)
{
this.name=name; f=new Frame("testrw");
f.addWindowListener(this);
b=new Button("保存文件");
o=new Button("打开文件");
o.setActionCommand("open");
b.setActionCommand("save");
o.addActionListener(this);
b.addActionListener(this);
ta=new TextArea(30,40);
f.add(ta,BorderLayout.SOUTH);
f.add(b,BorderLayout.CENTER);
f.add(o,BorderLayout.NORTH);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String cmd=e.getActionCommand();
try
{ if(cmd.equals("open"))
{
FileReader fr=new FileReader(name);
LineNumberReader flir=new LineNumberReader(fr);
String str=flir.readLine();
while (str != null)
{
ta.setText(str);
str=flir.readLine();}
flir.close();
fr.close();
}
else
{
FileWriter fo=new FileWriter(name);
fo.write( ta.getText());
fo.close();
}
}
catch (IOException IOe)
{ System.out.println(e);
} } public void windowClosing(WindowEvent e)
{System.exit(0);}
}
import java.awt.*;
import java.awt.event.*;
public class testrw2 extends WindowAdapter implements ActionListener{ Frame f;
Button o,b;
String name;
TextArea ta;
public static void main(String[] args)
{ new testrw2(args[0]);}
public testrw2(String name)
{
this.name=name; f=new Frame("testrw");
f.addWindowListener(this);
b=new Button("保存文件");
o=new Button("打开文件");
o.setActionCommand("open");
b.setActionCommand("save");
o.addActionListener(this);
b.addActionListener(this);
ta=new TextArea(30,40);
f.add(ta,BorderLayout.SOUTH);
f.add(b,BorderLayout.CENTER);
f.add(o,BorderLayout.NORTH);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ String cmd=e.getActionCommand();
try
{ if(cmd.equals("open"))
{
FileReader fr=new FileReader(name);
LineNumberReader flir=new LineNumberReader(fr);
String str=flir.readLine();
while (str != null)
{
ta.setText(str);
str=flir.readLine();}
flir.close();
fr.close();
}
else
{
FileWriter fo=new FileWriter(name);
fo.write( ta.getText());
fo.close();
}
}
catch (IOException IOe)
{ System.out.println(e);
} } public void windowClosing(WindowEvent e)
{System.exit(0);}
}
LineNumberReader flir=new LineNumberReader(fr);
String str=flir.readLine();
while (str != null)
{
ta.setText(str);
str=flir.readLine();}
flir.close();
fr.close();
}
这里读了一行干吗就把flir和fr关闭了??
close要在while循环之外
这样的做法很不好,你应该用一个StringBuilder来存放买次读取的数据,再一次性的setText