如何从阵列中打印特定线?

时间:2014-09-30 11:09:50

标签: java file-handling

我正在尝试为我们的项目构建一个工资单系统,包括GUI和事件处理程序,但我在文件处理方面遇到了困难。

我有一个看起来像这样的文本文件

1 Miguel 491
2 Jasper 323
3 Will 363

我想从该文本中检索一行 输出

1 Miguel 491

这是我的代码:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.List;  
import java.util.Scanner; 
import javax.swing.*;

import java.awt.Label; import java.awt.event.*;

public class Main { public class panels extends JFrame{





         }
    public static void main(String[] args) {        

        JFrame frame = new JFrame("Payroll by Miggy");
        frame.setSize(400,300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Label idlabel;                     // Declare an Label instance called lblInput
        idlabel = new Label("Enter ID");
        JButton jbtok = new JButton("Ok");

        frame.add(jbtok);

        try {
            File f = new File("C:/Users/MIGXTREME/Desktop/Employee.txt");
            Scanner sc = new Scanner(f);

            List<Employee> people = new ArrayList<Employee>();

            while(sc.hasNextLine()){
                String line = sc.nextLine();
                String[] details = line.split(" ");
                int Id = Integer.parseInt(details[0]);
                String name = details[1];
                int rate = Integer.parseInt(details[2]);
                Employee p = new Employee(Id, name, rate);
                people.add(p);
            }

           for(Employee p: people){
                System.out.println(p.toString());
           }

        } catch (FileNotFoundException e) {         
            e.printStackTrace();
        }
    } }

class Employee{

    private int Id;
    private String name;
    private int rate;

    public Employee(int Id, String name, int rate){
        this.Id = Id;
        this.setName(name);
        this.rate = rate;
    }

  public int getId() {
    return Id; }


public void setGender(int Id) {
    this.Id = Id; }


public void setName(String name) {
    this.name = name; }


public String getName() {
    return name; }


public int getrate() {
    return rate; }


public void setrate(int rate) {
    this.rate = rate; }

public String toString(){
    return this.Id + " " + this.name + " " + this.rate*4; } }

2 个答案:

答案 0 :(得分:0)

查看RandomAccessFile类。这将有助于非顺序遍历文件。

答案 1 :(得分:0)

只是做:

for(Employee p: people){
    if(p.name.equals("Miguel")){
        System.out.println(p.toString());
        break;
    }
}