在java文件中查找详细信息

在java文件中查找详细信息,java,file,frame,Java,File,Frame,我编写了一些代码,通过GUI框架从文件中查找学生详细信息: 如果我成功输入数据并单击搜索按钮,它将正确打印详细信息 如果我再次单击“搜索”,它将打印“未找到” 我知道readLine()函数读取下一行,但我希望每次按下搜索按钮时都能从头开始。我该怎么做 下面是到目前为止我的代码 import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; class search extends Frame

我编写了一些代码,通过GUI框架从文件中查找学生详细信息:

  • 如果我成功输入数据并单击搜索按钮,它将正确打印详细信息
  • 如果我再次单击“搜索”,它将打印“未找到”
我知道readLine()函数读取下一行,但我希望每次按下搜索按钮时都能从头开始。我该怎么做

下面是到目前为止我的代码

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
class search extends Frame implements ActionListener
{
Label lname,lresult;
TextField name;
TextArea result;
Button search,exit;
char ar;
String lines;
int n;
FileReader fr=new FileReader("student.txt");
BufferedReader br=new BufferedReader(fr);
public search() throws Exception
{
    setTitle("student details");
    setLayout(new FlowLayout());
    lname=new Label("name :");
    lresult=new Label();
    name= new TextField(20);
    result= new TextArea(50,50);
    search=new Button("search");
    exit= new Button("exit");
    add(lname);
    add(name);
    add(search);
    add(exit);
    add(lresult);
    add(result);    
    search.addActionListener(this);
    exit.addActionListener(this);
    setVisible(true);
}
public void actionPerformed(ActionEvent ae) 
{
    try
    {           
        lines=br.readLine();
        if(ae.getSource()==search)
        {
            n=lines.indexOf(name.getText());
            if(n>-1)
            {
                lresult.setText(" name found");
                result.setText(lines);
            }
            else                    
            {
                lresult.setText("not found");
                result.setText("not found");
            }
        }
    }
    catch(Exception e)
    {
    }
    if(ae.getSource()==exit)
    {
        search.this.dispose();
    }
}
public static void main(String s[]) throws Exception
{
    search se= new search();
    se.setSize(400,200);
    se.setVisible(true);
}
}

移动到actionPerformed(..)方法中的代码下面,它应该可以正常工作

    FileReader fr=new FileReader("student.txt");
BufferedReader br=new BufferedReader(fr);

读取流时,标记当前位置的光标会随着每个字节的读取而向前移动。 当您初始化流一次时,当您读取超过一个点时,您将没有机会再次访问该部分。(除非您倒带流。)
因此,要么每次在文件上创建一个新的流,要么使用允许跳转的随机访问通道(使用
Bufferedreader.mark
reset
也可以实现这一点,尽管不是很理想)


还要注意,在处理器方法中只读取一行。要逐行读取文件,请使用while循环:

String currentLine = "";
while((currentLine = br.readLine()) != null) {
   //do the funky stuff
}
您可以使用重置读卡器的位置:

RandomAccessFile raf = new RandomAccessFile("student.txt", "rw");

public void actionPerformed (ActionEvent ae) {

    // Resets to the beginning of file
    raf.seek(0);

    // rest of the method

}

它的方法
readLine()
可以用与
BufferedReader
相同的方法使用。

现在无法搜索第二个学生记录。。。它说即使我在文件中写了学生的名字也找不到,因为文件有多行。将try放入
while((s=br.readline())!=null)
使用while循环时,如果我搜索它,它只显示最后一条记录。一旦找到文件,while循环就必须中断