Java BufferedFileReader跳过第一行

时间:2018-12-15 14:51:00

标签: java swing io text-files

我正在尝试使用BufferedFileReader读取带有已保存信息的文档。它运行良好,但始终会跳过代码的第一行。是因为我在for循环中调用readLine()吗?如果可以,我该如何更改?

private void createViewUser() {

    String[] stringFirstName = new String[10];
    String[] stringName = new String[10];
    String[] stringAge= new String[10];

    try {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        for (int i = 0; br.readLine() != null; i++) {

            stringFirstName[i] = br.readLine();
            stringName[i] = br.readLine();
            stringAge[i] = br.readLine();

            firstname[i] = new JTextField();
            firstname[i].setBounds(100, 100 + 50 * i, 100, 30);
            view.add(firstname[i]);

            name[i] = new JTextField();
            name[i].setBounds(200, 100 + 50 * i, 100, 30);
            view.add(name[i]);

            age[i] = new JTextField();
            age[i].setBounds(300, 100 + 50 * i, 100, 30);
            view.add(age[i]);

            firstname[i].setText(stringFirstName[i]);
            name[i].setText(stringName[i]);
            age[i].setText(stringAge[i]);

        }
        fr.close();
        br.close();



    } catch (IOException ex) {
        ex.printStackTrace();
    }


}

4 个答案:

答案 0 :(得分:0)

确实,每次进入for循环之前,您的程序都会读取一行并检查其是否不为null。 由于这种情况,您还将跳过一行。 (不确定是否需要) 您还可以自己得到答案;)

答案 1 :(得分:0)

您正在读取for循环的第一行:

for (int i = 0; br.readLine() /* HERE*/ != null; i++) {

您可以执行以下操作:

String line = br.readLine();
for(int i = 0; line != null ; i++){
       stringFirstName[i] = line;
       line = br.readLine();
}

答案 2 :(得分:0)

您好,您可以初始化String var进行修复:

guard let url = URL(string: "{app_url_scheme}://") else {
    return
}

SFSafariApplication.getActiveWindow {(activeWindow: SFSafariWindow?)in
    activeWindow?.openTab(with: url, makeActiveIfPossible: false, 
    completionHandler: { (activeTab: SFSafariTab?) in
        print("openTab completed")
    })
} 

它不起作用,因为它在循环验证String line = br.readLine(); for (int i = 0; line != null; i++) { stringFirstName[i] = line; stringName[i] = br.readLine(); stringAge[i] = br.readLine(); 上加载了第一行

祝你好运。

答案 3 :(得分:0)

您的问题涉及几个步骤,但是对您而言,最重要的问题是当数据以三行显示时,如何有效地安全地读取文本文件中的数据:

first_name_1
last_name_1
age_1
first_name_2
last_name_2
age_2
first_name_3
last_name_3
age_3
first_name_4
last_name_4
age_4

当然,在哪里名称会被替换为真实名称,同样地,age_也会被替换?被一个实数代替。

如果您要走BufferedReader路线,我认为最安全的方法是在while循环的布尔条件下,在每个分组中都获得所有三个字符串,例如:

BufferedReader reader = new BufferedReader(....);

// declare empty Strings first
String firstName = "";
String lastName = "";
String ageString = ""; // need to get age *first* as a String

while ((firstName = reader.readLine()) != null         // get all 3 Strings here
        && (lastName = reader.readLine()) != null
        && (ageString = reader.readLine()) != null) {  // boolean condition ends here
    int age = Integer.parseInt(ageString.trim());    // NumberFormatException risk here

    // ....

}

这样,如果文本文件中缺少任何字符串,则整个while循环结束,并且不会获得错误的数据。

其他建议,创建一个普通的Java对象来保存您的Person数据,名称和年龄,一个具有3个字段的类,两个是名称字符串的String和一个用于年龄的int字段。给它一个像样的构造函数,getter方法。...例如:

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
    }

}

这样,上面的while循环可用于简单地创建Person对象:

List<Person> persons = new ArrayList<>();  // an ArrayList of Person to hold the data

while ((firstName = reader.readLine()) != null              // get all 3 Strings here
        && (lastName = reader.readLine()) != null
        && (ageString = reader.readLine()) != null) {       // the while loop ends here
    int age = Integer.parseInt(ageString.trim());

    Person person = new Person(firstName, lastName, age);   // create a new Person object 
    persons.add(person);                                    // put it into the arraylist
}

好吧,如何将这些信息显示到JTable中呢?

使用正确的列名称创建DefaultTableModel:

private static final String[] COL_NAMES = { "First Name", "Last Name", "Age" };
private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);

,然后使用此模型创建一个JTable:

private JTable table = new JTable(model);

然后遍历ArrayList<Person>并用数据填充我们的模型:

for (Person person : personList) {
    Vector<Object> rowData = new Vector<>();
    rowData.add(person.getFirstName());
    rowData.add(person.getLastName());
    rowData.add(person.getAge());
    model.addRow(rowData);
}

就像这样创建并填充数据的JTable。

好吧,假设一个名为PersonData.txt的数据文件与我们的类文件位于同一目录中,如下所示:

enter image description here

并假设该文件像这样保存我们的数据:

John
Smith
21
Fred
Flinstone
53
Barny
Rubble
52
Mary
Contrary
22
Bo
Peep
12
Donald
Trump
75
Donald
Duck
40
Mickey
Mouse
45
Minnie
Mouse
41
Ebenezer
Scrooge
80
Bob
Cratchit
33
Ralph
Kramden
55
Alice
Kramden
48
Ed
Norton
54

然后使用Person.java类,我们可以创建一个GUI来保存和显示我们的数据,如下所示:

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class PersonDisplay extends JPanel {
    private static final String[] COL_NAMES = { "First Name", "Last Name", "Age" };
    private static final String PERSON_DATA_PATH = "PersonData.txt";
    private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
    private JTable table = new JTable(model);

    public PersonDisplay(List<Person> personList) {
        for (Person person : personList) {
            Vector<Object> rowData = new Vector<>();
            rowData.add(person.getFirstName());
            rowData.add(person.getLastName());
            rowData.add(person.getAge());
            model.addRow(rowData);
        }

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    private static void createAndShowGui(List<Person> personList) {
        PersonDisplay mainPanel = new PersonDisplay(personList);

        JFrame frame = new JFrame("Person Display");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static List<Person> readInPersons(InputStream is) throws IOException {
        List<Person> persons = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String firstName = "";
        String lastName = "";
        String ageString = "";

        while ((firstName = reader.readLine()) != null 
                && (lastName = reader.readLine()) != null
                && (ageString = reader.readLine()) != null) {
            int age = Integer.parseInt(ageString.trim());
            Person person = new Person(firstName, lastName, age);
            persons.add(person);
        }

        return persons;
    }

    public static void main(String[] args) {
        try {
            InputStream inputStream = PersonDisplay.class.getResourceAsStream(PERSON_DATA_PATH);
            List<Person> personList = readInPersons(inputStream);
            SwingUtilities.invokeLater(() -> createAndShowGui(personList));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

,并且显示时,它看起来像:

enter image description here

相关问题