import java.awt.*;
import java.awt.event.*;
import java.awt.Color.*;
import java.io.*;
class FileStream extends Frame implements ActionListener
{
TextArea ta=new TextArea("",10,30);
Button b=new Button("读取数据");
FileStream()
{
this.add(ta,"North");
this.add(b,"South");
b.addActionListener(this);
this.pack();
this.setVisible(true);
}
File file;
FileInputStream finStream;
BufferedReader br;
public void actionPerformed(ActionEvent e)
{
try
{
file=new File("E:\\test.txt");
finStream=new FileInputStream(file);
br=new BufferedReader(new InputStreamReader(finStream));
String strText=br.readLine();
while(br.readLine()!=null)
{
strText=br.readLine()+"\n";
}
ta.setText(strText);
}
catch(Exception ee){}
}
public static void main(String[] args)
{
new FileStream();
}
}
原代码逻辑如下:
while(br.readLine()!=null) //读一行
{
strText=br.readLine()+"\n"; //读下一行到strText中
}
ta.setText(strText); //最后循环结束后strText值为null,和期望值不同
修改为:
file = new File("d:\\test.txt");
finStream = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(finStream));
String strResult = "";
String strText;
while ((strText = br.readLine()) != null) {
strResult += strText + '\n';
}
ta.setText(strResult);
测试结果如下图:
用心回答每个问题,如果有帮助,请及时采纳答案好吗,非常感谢~~~
while(br.readLine()!=null)
{
strText=br.readLine()+"\n";
}
->
while((strText += br.readLine())!=null);