可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容,之后将内容增加到JTextArea。
BufferedReader bre = null;
try {
String file = "D:/test/test.txt";
bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
{
JTextArea.add(str);//此处将内容写入到JTextArea即可
};
备注: 流用完之后必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Test extends JFrame{
//t1.txt t2.txt放在根目录
String[] s={"t1.txt","t2.txt"};
private JTextArea t=new JTextArea();
private JComboBox c=new JComboBox();
private JPanel p=new JPanel();;
private Toolkit k=Toolkit.getDefaultToolkit();
private Dimension screen=k.getScreenSize();
private JScrollPane js=new JScrollPane();
public Test(){
setVisible(true);
setSize(500, 500);
setLocation(screen.width/2-250,screen.height/2-250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setVisible(true);
p.setLayout(new BorderLayout());
add(p);
js.add(t);
js.setVisible(true);
js.setViewportView(t);
for(String ss:s){
c.addItem(ss);
}
p.add(c,BorderLayout.NORTH);
p.add(js,BorderLayout.CENTER);
c.addActionListener(new Action());
}
public static void main(String[] arg){
new Test();
}
class Action implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
t.setText("");
String item=(String) c.getSelectedItem();
String temp=null;
try {
BufferedReader br=new BufferedReader(new FileReader(item));
while((temp=br.readLine())!=null){
t.append(temp+"\n");
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
}
凑热门,读当前目录
js.setViewportView(t);
java.io.File cur=new java.io.File("."); // ----------------
for(String ss:cur.list()){ //
循环读取呗