简体   繁体   中英

How do I set the field variables in a method to data being read in from a .txt file in Java?

I have my default constructor set to at the moment.

//Default constructor
public MyInfo(String args) {
    Name = "";
    DateOfBirth = "";
    Location = "";
    AvgTemp = 0;
}

Since I am not sure what your actual .txt file looks like im going to assume that each line has Name,DateOfBirth,Location,AvgTemp.

Using a buffered reader, read the lines within a while loop and assign each value in an array after splitting the line by commas for example. Make sure to change your current variables to arrays before doing this.

BufferedReader br = new BufferedReader(new FileReader("Filename.txt"));
while (somevariable!=null){
somevairable=br.readLine();
String[] parts = somevariable.split(",");
Names[x]=parts[1]

And I will leave the rest up to you. Hopefully this is a decent start and you can follow the instructions. I suggest reading up on different types of file and buffered readers and writers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM