The error is that the customers has different ID, but in readCustomer object of ArrayList class the only ID that is saved is the ID of the last customer.
//reads customer data from register.txt file
//has 2 string as arguments
//returns a ArrayList object with all the customer with the same name
public ArrayList<Customer> readCustomer(String name,String surname){
Customer temp = new Customer();
//will hold all the customers with the same name and surname
ArrayList<Customer> readCustomer = new ArrayList<Customer>();
try{
FileInputStream fstream = new FileInputStream("register.txt");
BufferedReader fbr = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = fbr.readLine()) != null) {
String line[];
line = strLine.split(" ");
if(name.equals(line[1]) && surname.equals(line[2])){
temp.setCustomerID(Integer.parseInt(line[0]));
temp.setName(line[1]);
temp.setSurname(line[2]);
temp.setAddress(line[3]);
temp.setAge(Integer.parseInt(line[4]));
readCustomer.add(temp);
}
}
fbr.close();
}
catch(Exception ex){*emphasized text*
System.out.println(ex.getMessage());
}
return readCustomer;
}
Create a new object on every iteration and not one which gets filled recuringly. Also, learn to understand object references.
while ((strLine = fbr.readLine()) != null) {
Customer temp = new Customer();
// and so on
Use
Customer temp;//instead of doing Customer temp = new Customer();
And inside iteration do
temp = new Customer();
In every loop a new temp instance is created and thus you can add new customers to the array list as needed for your case.
You are creating the Consumer object only once all the way at the top. That means, every time you are just updating the same object with different values, and adding it to the list. So, you need to create the Consumer object for each and every record that you read from the text file. (i.e) You need to put the following line with in the while loop,
Customer temp = new Customer();
Related
I have a file name 1.txt
Coupe 1 2
Coupe 3 4
and I have a code
br = new BufferedReader(new FileReader("1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
String[] s = tmp.split("\\s");
comfortName = s[0];
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());
// next code send to constructor of class from value of comfort name a parametrs.
Class[] e = new Class[]{Integer.TYPE,Integer.TYPE};
comfortName = "second.objects.carriages.type." + comfortName;
Class carriageClass = Class.forName(comfortName); Constructor constructor = carriageClass.getDeclaredConstructor(e);
passenger = (Passenger) constructor.newInstance((tickets),(baggage));
// the next line add to list a value from constructor
carriage.addPassenger(passenger);
add passenger code:
public boolean addPassenger(Passenger passenger) {
totalPassenger +=Passenger.getTickets();
totalBaggage+=Passenger.getBaggage();
return Carriage.getPassengerList() .add(passenger);
}
So the result when I send it to list have something like that:
Coupe 3 4
Coupe 3 4
But from debugger I see that values reading good. but always the last row
overwrites the values of the previous lines in list .
So when I send only one row it's working
You have a typo in your code
I believe you should get tickets and baggage from the splitted array
tickets = Integer.parseInt(s[1]);
baggage = Integer.parseInt(s[2]);
instead of reading next lines, below will throw exception
tickets = Integer.parseInt(br.readLine());
baggage = Integer.parseInt(br.readLine());
The java.lang.Class.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
This sample code is working fine for me.
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/src/1.txt"));
String tmp = "";
while ((tmp = br.readLine()) != null) {
String[] s = tmp.split("\\s+");
String comfortName = s[0];
int tickets = Integer.parseInt(s[1]);
int baggage = Integer.parseInt(s[2]);
System.out.println(comfortName + tickets + baggage);
}
br.close();
}
on console :
Coupe12
Coupe34
Check your Passenger constructor that you create instance.
passenger = (Passenger) constructor.newInstance((tickets),(baggage));
The problem is at you constructor. If you constructor create new instance of Passenger object it will be ok. You constructor should be like that:
private Passenger(int tickets, int baggage){
this.tickets = tickets;
this.baggage = baggage;
}
I have an ArrayList of Objects and i want to store them into the file and also i want to read them from the file to ArrayList. I can successfully write them into the file using writeObject method but when reading from the file to ArrayList, i can only read first object. Here is my code for reading from serialized file
public void loadFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
myStudentList = (ArrayList<Student>) ois.readObject();
}
EDIT:
This is the code for writing list into the file.
public void saveToFile(ArrayList<Student> list) throws IOException {
ObjectOutputStream out = null;
if (!file.exists ()) out = new ObjectOutputStream (new FileOutputStream (file));
else out = new AppendableObjectOutputStream (new FileOutputStream (file, true));
out.writeObject(list);
}
Rest of my class is
public class Student implements Serializable {
String name;
String surname;
int ID;
public ArrayList<Student> myStudentList = new ArrayList<Student>();
File file = new File("src/files/students.txt");
public Student(String namex, String surnamex, int IDx) {
this.name = namex;
this.surname = surnamex;
this.ID = IDx;
}
public Student(){}
//Getters and Setters
public void add() {
Scanner input = new Scanner(System.in);
System.out.println("name");
String name = input.nextLine();
System.out.println("surname");
String surname = input.nextLine();
System.out.println("ID");
int ID = input.nextInt();
Ogrenci studenttemp = new Ogrenci(name, surname, ID);
myOgrenciList.add(studenttemp);
try {
saveToFile(myOgrenciList, true);
}
catch (IOException e){
e.printStackTrace();
}
}
Ok so you are storing whole list of students every time when new student comes in, so basicly what your file is keeping is:
List with one student
List with two students including the first one
List of 3 studens
and so on and so on.
I know you are probably thought it will write only new students in incremental fashion, but you were wrong here
.
You should rather add all students you want to store, into the list first. And then store complete list into the file , just like you are doing it.
Now, when you will be reading from the filre, first readObject will return you the list no.1 - that is why you are getting list with only one student. Second read would give you list no.2 and so on.
So you save your data you either have to:
Create complete list containig N students and store it once ito the file
Do not use list, but store students directly to the file
To read it back:
readObject once, so you will get List<Students>
Read students one by one from the file by multiple calls to readObject
This is Because I think ObjectOutputStream will return the first object from a file.
If you want all of the objects you can use for loop and use like this -:
FileInputStream fis = new FileInputStream("OutObject.txt");
for(int i=0;i<3;i++) {
ObjectInputStream ois = new ObjectInputStream(fis);
Employee emp2 = (Employee) ois.readObject();
System.out.println("Name: " + emp2.getName());
System.out.println("D.O.B.: " + emp2.getSirName());
System.out.println("Department: " + emp2.getId());
}
I'm struggling to figure out how to read the data from a file we've been given and use that to create an instance of an object. We are given a txt file of customer data for a store. It is in the following format:
123.64382392 12 1.1234123419
Each line of the file is like this. The first column is Arrival time, the second is number of items, and the third is the time it takes the customer to find one item. There are about 100 customers in this file and I'm not sure how to read from the file to create all the instances necessary.
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
double arrivalTime = input.nextDouble();
int numItems = input.nextInt();
double selectionTime= input.nextDouble();
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Try this:
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
List<Customer> list = new ArrayList<Customer>();
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
String[] values = scan.nextLine().split("\\s+");
arrivalTime = Double.parseDouble(values[0]);
numItems = Integer.parseInt(values[1]);
selectionTime = Double.parseDouble(values[2]);
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
list.add(newCustomer);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Could you elaborate on what part of your code isn't working? I tested it myself (printed out the values instead of creating a new Customer object), and it works fine. Except "input.nextLine();" in the while loop is not necessary. It will already jump to the next line, and once you reach the end of your file that will likely cause an error to be thrown.
Also, once you create the object instance, I assume you'll want to save it to a list of the objects. You can do this by creating an ArrayList of object Customer outside the loop:
ArrayList<Customer> Customers = new ArrayList<Customer>();
Then as each instance is created in the loop, add it to this ArrayList:
Customers.add(newCustomer);
I was trying to read a .txt file and wanted to store it in a hasmap(String, List). But when it tried to store the values were overwritten with the last value.
String filePath = "D:/liwc_new.txt";
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String key = null;
List<String> value = new ArrayList<String>();
//putting words in key and cat strings in value of map
int count = 0;
String cats[]= null;
value.clear();
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(":", 2);
value.clear();
count++;
key = parts[0].trim();
cats=parts[1].split(", ");
for(int i=0;i<cats.length;i++) {
cats[i]=cats[i].trim();
cats[i]=cats[i].replace("[", "");
cats[i]=cats[i].replace("]", "");
value.add(cats[i]);
}
map.put(key, value);
//map.put(key, value);
}
The line List<String> value = new ArrayList<String>(); should be moved to the first line of your while loop and both calls to clear removed.
The reason they are getting overwritten is you only ever allocate one list and put it in every value of the k:v pair of the map. So for every category, you have the same list, and the contents of that list are cleared and rebuilt every time a new line is read. So every value will have the contents of whatever was added after the last clear.
On the other hand, if you create a new list with each iteration, each category will have it's own list, what you want.
Delete the second occurrence of
value.clear();
i'm having some trouble with reading from a text file back and writing back to an array list. I was wondering if you could tell me where I'm going wrong? Thanks.
accountArrayList = new ArrayList<BankAccount>();
private void fileIn()
{
try
{
createTestAccounts();
//Scanner input = new Scanner(new FileReader(bankFile));
JOptionPane.showMessageDialog(null, "File: " + bankFile + " has been opened for importing");
BufferedReader reader = new BufferedReader(new FileReader("bankFile.txt"));
String account = reader.readLine();
while(account !=null) {
accountArrayList.add(account); // - add a new account to the text file, but exception show that String cannot be converted to Bank Account
account = reader.readLine();
}
reader.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "not found");
}
}
You are adding a String, but the list.add method expects an object of type BankAccount.
You'll have to find a way to turn that String into an Object of that type , then add the latter. Maybe there is a fromString() factory method? Or a Constructor that takes an initialization - String ?
If there is a constructor then it should look like
accountArrayList.add(new BankAccount(account));
To read all lines you may use (if your file is in UTF-8):
List<String> allLines = Files.readAllLines("bankFile.txt", StandardCharsets.UTF_8);
But as it was mentioned in the other comments you will need to transform a String into a BankAccount
BankAccount ba = new BankAccount(account);
accountArrayList.add(ba);
You're going to need something like this...depending on what your BankAccount class is exactly.
Assuming you have a String constructor for BankAccount, something like this:
public BankAccount(String account) {
this.account = account;
}
You can use Apache commons-io and java 8 to get a one-liner!
List<BankAccount> accounts = FileUtils.readLines(new File(filename))
.stream().map(BankAccount::new).collect(Collectors.toList());
The arraylist expects an BankAccount object, instead you are reading from a file, so the arraylist should be String.
ArrayList<String> accountArrayList = new ArrayList<>();
For the while loop condition, personally, i always use, but you can do it like that too.
while((account = reader.readLine()) != null){
accountArrayList.add(account);
}