Java 写入.dat文件,递增数字

Java 写入.dat文件,递增数字,java,output,increment,Java,Output,Increment,我正在写一个.dat文件。代码如下: String quit = ""; while(!quit.equals("quit")){ number = number + 1; int pid = number; String firstName = JOptionPane.showInputDialog("Give a first name to the Customer:"); String lastName = JOptionPa

我正在写一个.dat文件。代码如下:

    String quit = "";
    while(!quit.equals("quit")){ 


     number = number + 1;
     int pid = number; 
     String firstName = JOptionPane.showInputDialog("Give a first name to the Customer:");
     String lastName = JOptionPane.showInputDialog("Give a surname to the Customer:"); 
     String profession = JOptionPane.showInputDialog("Set the profession of the Customer:");
     quit = JOptionPane.showInputDialog("If you are finished, type quit. Otherwise, press any key:");
     boolean append = true;
     out = new BufferedWriter ( new FileWriter("C:\\Temp\\persons.dat", append));// open the file for writing

     out.write (Integer.toString( pid) );
     out.newLine(); 
     out.write ( firstName );
     out.newLine();
     out.write ( lastName );
     out.newLine();
     out.write (profession);
     out.newLine();
     out.newLine();
 out.close();
如果我知道f.ex。输入John作为名字,Smith作为姓氏,builder作为职业,这将是代码中的输出: 1. 约翰 史密斯 建筑商


但是,如果我再次运行代码,pid->person ID将再次从1开始,但我希望它计算出输入了多少不同的人,并从那里继续递增。我猜这很容易做到,但我的大脑已经停止工作了。

每次运行此操作时,数字都会重新初始化为0。为了实现这一点,您必须先从文件中读入数字,然后再将新数字写入文件。

每次运行此操作时,数字将重新初始化为0。为了实现这一点,您必须先从文件中读取数字,然后再将新数字写入文件。

您的
number
变量似乎是该方法的局部变量,或者至少在每次启动程序时将其初始化为
0

您需要做的是使其成为类成员,并将其初始化为输出文件中可用的记录数,即在类的构造函数中,您可以通过调用方法来初始化成员变量
number
,例如,让我们调用它
readPersons()
,它读取输出文件(如果可用),解析它,然后确定到目前为止输入了多少条记录

这是您需要的一项功能(如果还没有),用于在输出文件中显示人员

如果您还没有,那么我建议创建一个用于拯救人员的类:

public class Person {
    int pid;
    String firstName, lastName, profession;
}
然后,读取persons的方法应返回Person对象的
列表

List<Person> readPersons() {
    List<Person> persons = new ArrayList<Person>();
    // open file for reading
    // read line by line
    // once you have red all data for a person,
    // create a Person object an add it to the List persons
    return persons;
}

您的
number
变量似乎是该方法的局部变量,或者至少在每次启动程序时它都被初始化为
0

您需要做的是使其成为类成员,并将其初始化为输出文件中可用的记录数,即在类的构造函数中,您可以通过调用方法来初始化成员变量
number
,例如,让我们调用它
readPersons()
,它读取输出文件(如果可用),解析它,然后确定到目前为止输入了多少条记录

这是您需要的一项功能(如果还没有),用于在输出文件中显示人员

如果您还没有,那么我建议创建一个用于拯救人员的类:

public class Person {
    int pid;
    String firstName, lastName, profession;
}
然后,读取persons的方法应返回Person对象的
列表

List<Person> readPersons() {
    List<Person> persons = new ArrayList<Person>();
    // open file for reading
    // read line by line
    // once you have red all data for a person,
    // create a Person object an add it to the List persons
    return persons;
}

类似于:newfilereader(“C:\\Temp\\count.dat”).readLine()。我对文件读取器API不是非常熟悉,但我建议阅读一个单独的存储计数的文件。您可能还会看到@A4L left的答案,比如:newfilereader(“C:\\Temp\\count.dat”).readLine()。我对文件读取器API不是非常熟悉,但我建议阅读一个单独的存储计数的文件。您还可以查看答案@A4L left