how to read and search data from file (txt) and then display the data in TextArea or Jtable. for example I have file txt contains data and I need to display this data in textarea after I clicked a button, I have used FileReader , and t1 t2 tp are attributes in the file
import java.io.FileReader;
import java.io.IOException;
String t1,t2,tp;
Ffile f1= new Ffile();
FileReader fin = new FileReader("test2.txt");
Scanner src = new Scanner(fin);
while (src.hasNext()) {
t1 = src.next();
textarea.setText(t1);
t2 = src.next();
textarea.setText(t2);
tp = src.next();
textarea.setText(tp);
f1.insert(t1,t2,tp);
}
fin.close();
also I have used the inputstream
DataInputStream dis = null;
String dbRecord = null;
try {
File f = new File("text2.text");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream
while ( (dbRecord = dis.readLine()) != null) {
StringTokenizer st = new StringTokenizer(dbRecord, ":");
String t1 = st.nextToken();
String t2 = st.nextToken();
String tp = st.nextToken();
textarea.setText(textarea.getText()+t1);
textarea.setText(textarea.getText()+t2);
textarea.setText(textarea.getText()+tp);
}
} catch (IOException e) {
// catch io errors from FileInputStream or readLine()
System.out.println("Uh oh, got an IOException error: " + e.getMessage());
} finally {
}
but both of them don't work ,so please any one help me I want to know how to read data and also search it from file and i need to display the data in textarea .
thanks in advance
update the question
Firstly, thank you so much for those who answered my question.
secondly, To explain more , I want to read data from a file and display it in a TextArea so anyone have code to do this please show it to me becuase I have tried a lot and I still have same pro开发者_如何转开发blem.
textArea.setText(...);
replaces the existing text in the text area. I think you are looking for
textArea.append(...);
//Import necessary packages
public class FileRead implements ActionListener {
JFrame jf=new JFrame("Sample");
JTextArea jt=new JTextArea();
JButton jb=new JButton("Click Me");
public FileRead()
{
jf.setSize(300,200);
jt.setLayout(new BorderLayout());
jf.add(jb,BorderLayout.NORTH);
jf.add(jt,BorderLayout.CENTER);
jb.addActionListener(this);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} public static void main(String as[]) { new FileRead(); }
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb)
{
File f=new File("D:\\a.txt");
try
{
Scanner s=new Scanner(f);
while(s.hasNext())
{
jt.append(s.nextLine());
jt.append("\n");
}
}
catch(Exception ex)
{
System.out.println(""+ex);
}
}
}
}
精彩评论