How to input the data from a txt file into a arraylist. Involving multiple data types and class objects that are variables for other classes
I'm reading in data from different txt files to make objects and then into arraylists of the objects.
just as an example I have a teacher class with 3 or 4 varibles
public class Teacher {
public static String teacherNo;
public static String firstName;
public static String lastName;
public static Courses coursestought;
and a class Courses
public class Course {
public static String cC开发者_运维知识库ode;
public static String cName;
the constructor for the teacher class is like this
// constructor
public Teacher(String teacher_No,String first_Name,String last_Name,
Course coursesTought,)
I have all the right getters and setters(I think)
I read from the text file like this.
BufferedReader inFile = new BufferedReader (new FileReader
("pathtofile/teachers.txt"));
And I create the Teacher objects like this
String inputLine;
inputLine = inFile.readLine();
while (inputLine != null)
{
teacherlist.add(new Teacher
(inputLine, inputLine, inputLine, inputLine,));
inputLine = inFile.readLine();
}
But this only works if all the fields are strings not a mix of strings and variables and objects. The fields in the text file are 1 line to a teacher and separated by :
Can someone point me in the right direction here?
Do I need to cut up the strings as I read them in ?
Yes. You need to use String#split() to split the strings once you read them, create your objects and then add them to your arraylist
List<Teacher> teachers = new ArrayList<Teacher>();
BufferedReader inFile = new BufferedReader (new FileReader
("pathtofile/teachers.txt"));
String inputLine;
while ( (inputLine = inFile.readLine() ) != null) { // read one line at a time
String[] teacherVars = inputLine.split(":"); // split into a string array.
teachers.add(new Teacher(teacherVars[0], teacherVars[1], teacherVars[2], teacherVars[3]);
}
Not very clear from your question how the Courses
object is represented in your text file. If thats variable length on the same line, you might have to do some additional magic to dynamically create the Courses
object and then create the Teacher
object.
Your instance variables inside class Teacher
and Courses
should not be static either. Static means class level and not object level.
If you have a Teacher class that looks like this ,
public class Teacher {
private String teacherNo;
...
private List<Course> courses;
public List<Course> getCourses() {
if ( courses == null)
courses = new ArrayList<Course>();
return courses;
}
}
then, you could call it like this within your while loop --
while ( (inputLine = input.readLine() ) != null ) {
Teacher teacher = new Teacher(teacherVar[0], teacherVar[1], teacherVar[2]);
Course aCourse = new Course(teacherVar[3], teacherVar[4]);
teacher.getCourses().add(aCourse);
}
This is assuming your teacher line in text has a course code and course name as part of it.
精彩评论