Write text file content into custom arraylist in Java - java

Suppose I have a text file DataBase.txt with the following content:
1 leo messi 12.12.1986
2 cristiano ronaldo 22.01.1985
3 arjen robben 14.11.1991
And a custom arraylist which looks like this:
public static ArrayList<Rows> InfoList = new ArrayList<Rows>();
This is my Rows class implementation with setters, getters and toString method:
public class Rows {
public int id;
public String firstName;
public String secondName;
public String dateOfbrth;
#Override
public String toString() {
return this.id + " " + this.firstName + " " +
this.secondName + " " + this.dateOfbrth;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getSecondName() {
return secondName;
}
public String getDateOfbrth() {
return dateOfbrth;
}
public void setId(int id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public void setDateOfbrth(String dateOfbrth) {
this.dateOfbrth = dateOfbrth;
}
}
So. the question is: How to write text file content into an arrayList where every element will be refered to its own field in class Rows. despite of different count of spaces in each line ? Which algorithms or Java classes will be useful to approach that ?
I'm novice in Java so I tried to do this using BuffredReader but I stuck with separating line and adding each element into arrayList:
try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
for (String line; (line = br.readLine()) != null; ) {
}
}
Thanks for any help

This is the way:
try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
String line;
while((line = br.readLine())!=null ) {
String[] values = line.split("\\s+");
...
}
}

while ((line = br.readLine()) != null) {
String[] row = line.split("\\s+");
Row row = new Row();
row.setId(row[0]);
row.setFirstName(row[1]);
row.setSecondName(row[2]);
row.setDateOfbrth(row[3]);
InfoList.add(row);
}
\s+ is a regex expression which will cause any number of consecutive spaces to split your string into tokens, see this answer How to split a String by space
Hope it helps.

Related

Why is FileReader not reading beyond the end of the first line?

I'm trying to read in data from a text file using FileReader. There are four lines of text. Each line has the same attribute types (first name, last name, dob, ssn, etc.). I am trying to split the data read in by the " " delimiter into one long array and then assign the values to a record ArrayList. My logic (if you can even call it that), is that by doing this I'd have one giant array of String data which I could then assign to each of the record's 7 fields - 0-6 for the first record, 7-13 for the second record, 14-20 for the third... But it looks like my while loop is stopping at the end of line one. I feel really stupid here, but I cannot figure out how to get this to work. And yes, I know, there is a lot that is bad form in my code, but I'm just trying to get a feel for the functionality. Any advice here would be most appreciated. Thank you!
The text file looks like this:
John Smith 1996.03.07 123-45-6789 Chickenpox BedRest aspirin
Joe Blow 1996.03.07 123-45-6888 Smallpox BedRest Whiskey
Julie Wilson 1996.03.07 123-45-6999 Insomnia Exercise HotPeppers
Wayne Blaine 1942.07.07 123-45-6777 Measles WaitToGetBetter CodLiverOil
Here's my main.
public static void main(String [] args) throws Exception {
String line = "";
BlockRecord record0 = null;
BlockRecord record1 = null;
BlockRecord record2 = null;
BlockRecord record3 = null;
try {
ArrayList<String> data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
record0 = new BlockRecord();
record1 = new BlockRecord();
record2 = new BlockRecord();
record3 = new BlockRecord();
record0.setBlockID(new String(UUID.randomUUID().toString()));
record1.setBlockID(new String(UUID.randomUUID().toString()));
record2.setBlockID(new String(UUID.randomUUID().toString()));
record3.setBlockID(new String(UUID.randomUUID().toString()));
//manually set until more functionality is in place
data = line.split(" ");
record0.setFirstName(data[0]);
record0.setLastName(data[1]);
record0.setDob(data[2]);
record0.setSsn(data[3]);
record0.setDiagnosis(data[4]);
record0.setTreatment(data[5]);
record0.setRx(data[6]);
record1.setFirstName(data[7]);
record1.setLastName(data[8]);
record1.setDob(data[9]);
record1.setSsn(data[10]);
record1.setDiagnosis(data[11]);
record1.setTreatment(data[12]);
record1.setRx(data[13]);
record2.setFirstName(data[14]);
record2.setLastName(data[15]);
record2.setDob(data[16]);
record2.setSsn(data[17]);
record2.setDiagnosis(data[18]);
record2.setTreatment(data[19]);
record2.setRx(data[20]);
record3.setFirstName(data[21]);
record3.setLastName(data[22]);
record3.setDob(data[23]);
record3.setSsn(data[24]);
record3.setDiagnosis(data[25]);
record3.setTreatment(data[26]);
record3.setRx(data[27]);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Here's my BlockRecord class:
class BlockRecord{
String firstName;
String lastName;
String ssn;
String dob;
String diagnosis;
String treatment;
String rx;
String seed;
String winner;
String blockID;
String previousHash;
String verificationID = "0";
String uuid = UUID.randomUUID().toString();
String winningHash;
public static KeyPair keyPair;
public static int recordCount;
public String getWinningHash() {
return winningHash;
}
public void setWinningHash(String winningHash) {
this.winningHash = winningHash;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
public String getTreatment() {
return treatment;
}
public void setTreatment(String treatment) {
this.treatment = treatment;
}
public String getRx() {
return rx;
}
public void setRx(String rx) {
this.rx = rx;
}
public String getSeed() {
return seed;
}
public void setSeed(String seed) {
this.seed = seed;
}
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getBlockID() {
return blockID;
}
public void setBlockID(String blockID) {
this.blockID = blockID;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getVerificationID() {
return verificationID;
}
public void setVerificationID(String verificationID) {
this.verificationID = verificationID;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
You read all the lines and add each on them to the list data in the loop:
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
But then, you only split line, which is the last read line.
data = line.split(" ");
Quick fix:
Merge all the lines into one. Then split it.
String mergedLines = "";
while((line = reader.readLine()) != null) {
System.out.println(line);
mergedLines = mergedLines + line;
}
This is really dirty and uneffective as the file already provides separated records.
Better solution:
Create a BlockRecordfor each line without merging them. Then store the record in a list.
ArrayList<BlockRecord> allRecords = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data = line.split(" ");
BlockRecord record = new BlockRecord()
record.setFirstName(data[0]);
record.setLastName(data[1]);
record.setDob(data[2]);
record.setSsn(data[3]);
record.setDiagnosis(data[4]);
record.setTreatment(data[5]);
record.setRx(data[6]);
allRecords.add(record)
}
This way, you don't even have to know how many records to declare before reading

Loading and editing a CSV file in Java into a List

I'm working on a private project where i need to load a CSV file, keep it in the program and edit if needed.
The file looks like this:
ID;Name;Last Login;RevState;List
157;Guy;"01.11.19";false;"tag, cup, sting"
A60;Dud;"07.10.19";true;"ice, wood, cup, tag"
1D5;Wilfred;"11.11.19";true;"beer, food, cup, shower"
I will only ever have a single csv file loaded. I need to be able to edit every single data point. I need to be able to retrieve all the information of one "category", e.g. get all names.
So what I plan to do is load the CSV via
Scanner scanner = new Scanner(new File(file.csv))
Create a class that holds the information of a line
public class User
private String id;
private String name;
private String lastLogin;
private String list;
public getter and setter methods
Create a list
private List<User> csvList = new List<User>();
And then store every line as
while (file.hasNextLine())
[...] parse the line
User user = new User(id, name, lastLogin, list);
csvList.add(user);
Would this work, or is there a better method that I can't think of right now?
Here it goes:
public class User {
private int id;
private String name;
private String email;
private String phone;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
Main class
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args ) throws Exception {
List<User> users = new ArrayList<>();
String path = System.getProperty("user.dir");
FileInputStream fileInputStream = new FileInputStream(path+"/src/"+"users.csv");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
int lines = 0;
while((line=bufferedReader.readLine())!=null){
lines++;
String [] columns = line.split(",");
if(lines ==1 ) {
continue;
}
else {
User user = new User();
user.setId(Integer.parseInt(columns[0]));
user.setName(columns[1]);
user.setEmail(columns[2]);
user.setPhone(columns[3]);
users.add(user);
}
}
for(int i=0;i< users.size();i++){
System.out.println(users.get(i));
}
}
}
And users.csv file
Id, Name, Email, Phone
1, John, john.doe#gmail.com, 123456789

JSoup HTML Parse and Write Results to CSV In Order

I am trying to find the best approach to saving the data I have parsed out of the HTML document when Jsoup into a CSV. The problem I'm having is using [CSVWriter][1] - https://mvnrepository.com/artifact/com.opencsv/opencsv/4.6 and writing the data with it. Please see my code snippet below. The structure of the data looks like the following with infobox being the main listing record with each subsequent field within it. The CSVWriter looks like it is a String Array but having trouble going from elements to write to the CSVData writer with a String Array.
The Jsoup selector is returning an array of items from the selection. For instance, when I make the selection for the name, it is returning all 9 names if there are 9 records on the page. I need to put this data together in order for each row to print into a CSV.
InfoBox >
Name|
Email|
Phone|
Website
The problem I'm having is how I'm trying to write the data on this line below
writer.writeAll((Iterable<String[]>) infoArray);
This is not working correctly and errors but wanted to show what I am kind of after and if there is somebody who's familiar with writing data from Jsoup Elements into CSV. Thanks
String filePath ="c:/results.csv";
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
List<String> infoArray = new ArrayList<>();
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
infoArray.add(infobox.get(i).select(".business-name > span").text());
infoArray.add(infobox.get(i).select(".phones.phone.primary").text());
infoArray.add(infobox.get(i).select(".street-address").text());
infoArray.add(infobox.get(i).select(".state").text());
infoArray.add(infobox.get(i).select(".city").text());
infoArray.add(infobox.get(i).select(".zip").text());
}
writer.writeNext(header);
//How to write data in order to match each record accordingly?
//Data should be written to CSV like the following example under each header into each corrosponding row
//name, phone, street
writer.writeAll((Iterable<String[]>) infoArray);
for(String ia : infoArray){
}
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here's what ended up working for me. The problem was not adding Strings into a String array to pass to CSVWriter. Here is my example.
try {
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
if(count == 0){
writer.writeNext(header);
}
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
String businessName = infobox.get(i).select(".business-name > span").text();
String phone = infobox.get(i).select(".phones.phone.primary").text();
String address = infobox.get(i).select(".street-address").text();
//Address seems to be displayed another way too
String address2 = infobox.get(i).select(".adr").text();
//Use regular expression to normalize data
String[] columns = new String[]{
businessName, phone, address
};
writer.writeNext(columns);
}
writer.close();
}
Here is little example how to use OpenCSV. Maybe will be helpful for you.
HeaderNames.java
public class HeaderNames
{
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String STREET = "Street";
public static final String STATE = "State";
public static final String CITY = "City";
public static final String ZIPCODE = "Zipcode";
}
DemoDTO.java
import java.io.Serializable;
import com.opencsv.bean.CsvBindByName;
public class DemoDTO implements Serializable
{
private static final long serialVersionUID = 1L;
#CsvBindByName(column = HeaderNames.NAME)
private String name;
#CsvBindByName(column = HeaderNames.PHONE)
private String phone;
#CsvBindByName(column = HeaderNames.STREET)
private String street;
#CsvBindByName(column = HeaderNames.STATE)
private String state;
#CsvBindByName(column = HeaderNames.CITY)
private String city;
#CsvBindByName(column = HeaderNames.ZIPCODE)
private String zipcode;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getZipcode()
{
return zipcode;
}
public void setZipcode(String zipcode)
{
this.zipcode = zipcode;
}
}
Main.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class Main
{
public static void main(String[] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException
{
File file = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "results.csv");
FileWriter writer = new FileWriter(file);
List<DemoDTO> beans = new ArrayList<DemoDTO>();
for (int i = 0; i < 10; i++)
{
DemoDTO demoDTO = new DemoDTO();
demoDTO.setCity("city " + i);
demoDTO.setName("name " + i);
demoDTO.setPhone("phone " + i);
demoDTO.setState("state " + i);
demoDTO.setStreet("street " + i);
demoDTO.setZipcode("zipcode " + i);
beans.add(demoDTO);
}
HeaderColumnNameMappingStrategy<DemoDTO> strategy = new HeaderColumnNameMappingStrategy<>();
strategy.setType(DemoDTO.class);
StatefulBeanToCsv<DemoDTO> beanToCsv = new StatefulBeanToCsvBuilder<DemoDTO>(writer)
.withSeparator(';')
.withEscapechar(CSVWriter.NO_ESCAPE_CHARACTER)
.withLineEnd(CSVWriter.DEFAULT_LINE_END)
.withQuotechar(CSVWriter.DEFAULT_QUOTE_CHARACTER)
.withMappingStrategy(strategy)
.withThrowExceptions(true)
.build();
beanToCsv.write(beans);
writer.flush();
writer.close();
}
}

Create method to count occurrences of type char within an array

I need to create a method that searches a String array whether a specfic character exists in the array and returns an integer of the number of occurrences the character appears, I have looked on other posts to try and work it out myself but they are all arrays of int not String
I have another class name hence the array name being type Name.
public class Reg {
//Fields
private ArrayList<Name> Name;
//Constructors
public Reg() {
Name = new ArrayList<>();
}
//Methods
public int CountCharacterOccurrences (Char character){
}
}
Name Class:
public class Name implements Comparable<Name> {
//Fields
private String firstName;
private String familyName;
//Constructors
public Name() {
firstName = "";
familyName = "";
}
public Name(String firstName, String familyName) {
this.firstName = firstName;
this.familyName = familyName;
}
//Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public String getFamilyName() {
return familyName;
}
public String getFullName() {
if (firstName.equals("") && familyName.equals("")) {
return "";
} else {
return firstName + " " + familyName;
}
}
#Override
public String toString() {
return "Name:[firstName=" + firstName + ", familyName=" + familyName + "]";
}
}
How do I add a method CountCharacterOccurences that accepts a char argument and returns an int signalling the number of occurrences.
Maybe this is what you mean:
class Reg{
private ArrayList<Name> names;
public Reg() {
names = new ArrayList<>();
}
public int countFirstNameOccurrences(char c) {
return names.stream() // get Stream<Name>
.map(Name::getFirstName) // convert Stream<Name> to Stream<String> using Name's firstName
.mapToInt(s -> s.length() - s.replace(String.valueOf(c), "").length()) // calculate every occurrence c in each firstName and get an IntStream
.sum(); // sum all the values
}
public static void main(String[] args) {
Reg reg = new Reg();
reg.names.add(new Name("John", "Doe"));
reg.names.add(new Name("Johnny ", "Doe"));
reg.names.add(new Name("Richard", "Roe"));
reg.names.add(new Name("James", "Roe"));
reg.names.add(new Name("Jane", "Roe"));
System.out.println(reg.countFirstNameOccurrences('J'));
}
}
Output:
4
as there are 4 J's in the first names in the list (John, Johnny, James and Jane)

Reading contents of a file into class objects

I have a text file of employee entries as follows:
000, first name1, middle name1
001, first name2, middle name2
002, first name3, middle name3
003, first name4, middle name4
004, first name5, middle name5
And I have a class Employee as follows:
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
}
I've read the contents of the file into an array. But what I want is to construct an array of objects of class Employee, and a way for each attribute of the class to be initialised with each entry. Something like this:
Employee e[] = new Employee[5];
Checking the details of each object in the array...
e[0].id = 000
e[0].fName = "first name1"
e[0].mName = "middle name1"
e[0].lName = "last name1"
Then,
e[1].id = 001
And so on...
Is there any way I can do this?
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
public Employee(String line) {
String[] split = line.split(",");
id = Integer.parseInt(split[0]);
fName = split[1];
mName = split[2];
lName = split[3];
}
}
Since you already read the file into array (of string I suppose).
String[] lines = ....;
Employee[] employees = new Employee[lines.length];
for(int i = 0; i < lines.length; i++) {
employees[i] = new Employee(lines[i]);
}
There you go... you have an array of employees.
Read the file and loop over its content line by line. Then parse the lines and create a new Employee() in each iteration. Set your values, such as id and name. Finally, add your new Employee instance to a List<Employee> and continue with the next entry.
// Read data from file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
// List to collect Employee objects
List<Employee> employees = new ArrayList<Employee>();
// Read file line by line
String line = "";
while ((line = br.readLine()) != null) {
// Parse line to extract individual fields
String[] data = this.parseLine(line);
// Create new Employee object
Employee employee = new Employee();
employee.id = Integer.valueOf(data[0]);
employee.fName = data[1];
employee.mName = data[2];
// Add object to list
employees.add(employee);
}
// Further process your Employee objects...
}
Also, there are CSV libraries that can handle all the nasty parts of reading a file that has comma separated values. I'd suggest using OpenCSV, for example.
Here already answers posted but I still gonna post mine...
package com.stackoverflow.java.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Employee {
public int id;
public String fName;
public String mName;
public Employee(int id, String fName, String mName) {
this.id = id;
this.fName = fName;
this.mName = mName;
}
public static void main(String[] args) throws IOException {
Employee[] e = new Employee[5];
FileReader fr=new FileReader("YourDoc.txt");
BufferedReader br=new BufferedReader(fr);
String line="";
String[] arrs=null;
int num=0;
while ((line=br.readLine())!=null) {
arrs=line.split(",");
e[num] = new Employee(Integer.valueOf(arrs[0]), arrs[1], arrs[2]);
num++;
}
br.close();
fr.close();
for(int i=0 ; i< e.length; i++) {
System.out.println(e[i].id + " and " + e[i].fName + " and " + e[i].mName);
}
}
}
try :
public static void main(String[] args) throws IOException {
File f1 = new File("d:\\data.txt");
Scanner scanner = new Scanner(f1);
List<Employee1> empList=new ArrayList<>();
while(scanner.hasNextLine()){
String data[]=scanner.nextLine().split(",");
empList.add(new Employee(Integer.parseInt(data[0]),data[1],data[2],data[3]));
}
scanner.close();
System.out.println(empList);
}
Employee.java
class Employee{
public int id;
public String fName;
public String mName;
public String lName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Employee(int id, String fName, String mName, String lName) {
super();
this.id = id;
this.fName = fName;
this.mName = mName;
this.lName = lName;
}
#Override
public String toString() {
return "Employee [id=" + id + ", fName=" + fName + ", mName="
+ mName + ", lName=" + lName + "]";
}
}

Categories

Resources