You can use a BufferedReader
to iterate over lines:
final BufferedReader reader = new BufferedReader(new FileReader("/path/to/file"));
String line;
while ((line = reader.readLine()) != null) {
// Create your object from the string
}
Question
I have two files and I want to individually read them then use the the first file to create 5 objects and then use the second file to add the parameters to be passed to a constructor, question is is I am not quite sure how to do that.
What I wanted to do was to loop the hasNextLine
and assign the next line to a string and have an object created from that string name, then passing variables in the same way but I see that may not be possible in Java. If it isn't what is another way I could approach this?
Well I was trying to do something like this
while(salesPersonScanner.hasNextLine()){
String personName = salesPersonScanner.nextLine();
SalesPerson personName = new SalesPerson();
}
Solution
You can use a BufferedReader
to iterate over lines:
final BufferedReader reader = new BufferedReader(new FileReader("/path/to/file"));
String line;
while ((line = reader.readLine()) != null) {
// Create your object from the string
}
OTHER TIPS
You have two options:
You can read all of the required parameters from files and then pass them all to the constructor to create a new object.
You can create an object with your constructor and use setters to set each of the instance variables.
I personally suggest the first approach unless you have to set lots of variables.