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);
Related
I've got a text file like this: https://i.stack.imgur.com/nL0Z4.png
The first column represents the user ID and the last column represents balance. I want to iterate through the elements to find a specific user ID and then update their balance. I've managed to match the user ID and access the balance using the Scanner but I'm not sure how to update the balance in the text file with a new value. This is the code I've written so far: I tried to take the elements, modify the balances and put the updated values in an arraylist. Then put them into the text file using PrintWriter. But I keep getting an empty text file when I call this function.
File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
ArrayList<String> items = new ArrayList<String>();
while(sc.hasNextLine()){
String info = sc.nextLine();
String data[] = info.split(" ");
if(String.valueOf(currentUser.getAccountNumber()).equals(data[0])){
data[3] = String.valueOf(currentUser.getBorrowBalance());
//Updating the balance in ArrayList
}else{
continue;
}
for(int i=0; i<data.length; i++){
items.add(data[i]);
}
}
PrintWriter pw = new PrintWriter(file);
for(int j=0; j<items.size(); j++) {
pw.printf("%s ", items.get(j));
if(j%3==0) pw.println(); //Going to new line after writing 4 elements to text file
}
pw.close();
sc.close();
I would highly reccomend to use Serialization for this. I am assumming you already have a Customer class with balance,id etc. With Serialization things are just as simple as getting the customer you want,updating his balance,and then writing in your file.For example:
customer = getCustomerById(selectedId);
customer.setBalance(newBalance);
customer.write();
And the write method would look like this
public void write(String filename) {
try {
File temp = new File(filename);
temp.createNewFile(); // create file if not present
FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
More on Serialization here
so I have a text file and i am trying to read line by line and then populate my array list.
a sample text file is shown below:
10,11,11/10/2021,24,1,2
11,12,11/10/2021,1,2,3
12,13,11/10/2021,24,5
13,14,11/10/2021,1,11,32,2
14,15,11/10/2021,1,9,8
I have been able to read in the first 4 elements (ID,ID,date,price)
and then i need to populate the other elements on that line into an array list (all elements after price)
the problem I am having is that it populates all the other lines into the array list and just not the remaining elements for the one line.
here is the code
int ID = 0;
int spareID = 0;
String date = "";
float fee = 0;
ArrayList<String> limits = new ArrayList<String>();
ArrayList<Import> imports= new ArrayList<Imports>();
File myfile = new File("file.txt");
try {
Scanner inputFile = new Scanner(myfile);
inputFile.useDelimiter(",");
// setting comma as delimiter pattern
while (inputFile.hasNextLine()) {
ID = inputFile.nextInt();
SpareID = inputFile.nextInt();
date = inputFile.next();
fee = inputFile.nextFloat();
while (inputFile.hasNext()) {
limits.add(inputFile.next());
}
Import import = new Import(ID, spareID, fee, date, limits);
imports.add(import);
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("error: can not find file");
}
the array list is capturing the rest of the text file when i need it to capture just the remaining elements on that line.
Edit: the first 4 elements of the line will all go into a different variable and then I need the rest or the elements on that line only to go into the array list
Use Scanner.nextLine() to get a single line, then create a second Scanner with that line to parse it contents.
Scanner inputFile = new Scanner(myfile);
while (inputFile.hasNextLine()) {
Scanner line = new Scanner(inputFile.nextLine());
// setting comma as delimiter pattern
line.useDelimiter(",");
ID = line.nextInt();
SpareID = line.nextInt();
date = line.next();
fee = line.nextFloat();
while (line.hasNext()) {
limits.add(line.next());
}
}
inputFile.close();
I'm trying to figure out how to delete a specific line in my Arraylist when a user types in a book ID number. However it seems that it can't find that ID number anywhere in my Arraylist.
private void removeBook()
// Removes a certain book from the Book List.
{
Scanner IDS = setbookID();
int idNum = IDS.nextInt();
if(bookList.contains(idNum)){ //problem
bookList.remove("B"+Integer.valueOf(idNum));
}
}
private Scanner setbookID(){
Scanner bookID = new Scanner(System.in);
System.out.println("Enter your book's ID number. ");
return bookID;}
bookList is an ArrayList that read through a text file and come out as a String. A line in my text file looks like this:
B998 ; Aithiopika ; Heliodorus ; 1829
However if the user types in "998" it doesn't remove this line from the ArrayList. Any ideas on how I can go about doing this? Would an iterator somewhat help?
EDIT: This is how I added the books to the ArrayList in the first place.
private ArrayList<Book> readBooks(String filename) {
ArrayList<Book> lines = new ArrayList<>();
readTextFileB(filename, lines);
return lines;
}
private void readTextFileB(String filename, ArrayList<Book> lines)
// Reads the books.txt file.
{
Scanner s = null;
File infile = new File(filename);
try{
FileInputStream fis = new FileInputStream(infile);
s = new Scanner(fis);
} catch (FileNotFoundException e){
e.printStackTrace();
}
while(s.hasNextLine())
lines.add(new Book(s.nextLine()));
}
You have multiple problems with your code. Not clear what you are trying to achieve whether you want to remove the Book object from the list. If so then you need to compare the ID field(using iterator) of the book object assuming your Book class is like below:
class Book {
int id;
Book(int id) {
this.id = id;
}
}
If above case is not the scenario then your list is a list of Book object then how can you pass String as parameter on the remove method bookList.remove("B"+Integer.valueOf(idNum));
you should pass Book object here or index number.
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());
}
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();