Parsing CSV file with #Parsed annotation in a Form - Univocity parser - java

I am trying to parse a CSV file with some #Parsed annotation in a form file but it's not working.
I am using univocity lib
Init.java
public static void main(String[] args) throws FileNotFoundException {
CsvParserSettings parserSettings = new CsvParserSettings();
BeanListProcessor<FireReportFormGeneral> rowProcessor = new BeanListProcessor<FireReportFormGeneral>(FireReportFormGeneral.class);
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(parserSettings);
parser.parse(new FileReader("/home/jose/Desktop/example.csv"));
List<FireReportFormGeneral> beans = rowProcessor.getBeans();
System.out.println(rowProcessor.getHeaders());
System.out.println(beans);
}
FireReportFormGeneral.java
#Parsed(field = "Account Number")
private String accountNumber;
#Parsed(field = "Account Type")
private String accountType;
#Parsed(field = "Bank Client Identification Number")
private String bankClientIdNumber;
#Parsed(field = "Account Opening Date")
private String accountOpeningDate;
//getters and setters
But my output is always something like:
[Ljava.lang.String;#7591083d
[com.opessoftware.fire.csv.reader.FireReportFormGeneral#77a567e1,
com.opessoftware.fire.csv.reader.FireReportFormGeneral#736e9adb]
For sure I am doing something wrong but I could not find the answer.
Thanks.
EDIT:
I solve the problem
The thing is if a call beans.get(index).getAccountName() for example it's going to return values for me.

You could add a toString() method to FireReportFormGeneral.java, then your System.out.println() should be more readable.
eg.
public String toString(){
return "Account number: " + accountNumber + " Account Type: " + accountType;
}
This is just a simple example, without null checks, StringBuilder etc...
Does this solve your problem?

Related

JSONArray to ArrayList in Android

I get jsonarray as following from server "dataArray":
[{"FirstNmae":"xyz","BranchId":"asd","Location":"qwe"}]
Now I want to create ArrayList<EmpData> list using Gson where EmpData is normal Pojo class. Below is my code which is getting error
TypeToken<List<EmpData>> token = new TypeToken<List<EmpData>>() {};
List<EmpData> empList = gson.fromJson(dataArray, token.getType());
Not an answer, but included as an answer to show formatted code.
Unable to reproduce. Here is a Minimal, Reproducible Example, based on the information in the question, and it runs fine.
The code uses public fields for simplicity. Real code would likely use private fields and getter/setter methods, but since the POJO is not the question, I kept this simple.
Gson gson = new Gson();
// Code from question starts here
String dataArray = "[{\"FirstNmae\":\"xyz\",\"BranchId\":\"asd\",\"Location\":\"qwe\"}]";
TypeToken<List<EmpData>> token = new TypeToken<List<EmpData>>() {};
List<EmpData> empList = gson.fromJson(dataArray, token.getType());
// Code from question ends here
System.out.println("dataArray = " + dataArray);
System.out.println("empList = " + empList);
class EmpData {
#SerializedName("FirstNmae")
public String firstName;
#SerializedName("BranchId")
public String branchId;
#SerializedName("Location")
public String location;
#Override
public String toString() {
return "EmpData[firstName=" + this.firstName +
", branchId=" + this.branchId +
", location=" + this.location + "]";
}
}
Output
dataArray = [{"FirstNmae":"xyz","BranchId":"asd","Location":"qwe"}]
empList = [EmpData[firstName=xyz, branchId=asd, location=qwe]]
Notice how the #SerializedName annotation is used to handle the typo in the name (FirstNmae), as well as the uppercase/lowercase issue of the first letter in the names.

Converting Enum to a String Object for Java seamlessly

I am shaky with parsing and handling text files. How do I convert my method signatures with enums to strings so I can read from a text file and parse effectively without wasting CPU resources? I currently have method signatures like this
public void createReservation(VehicleType v, String cName, long phoneNumber, String sDate, String eDate) throws Exception //right here
{
//trouble with representing VehicleType v in my Reservation text file
}
Reservation.txt file looks like this matching the signature Above
"COMPACT", "John Wick", 312 900 6001, "2019-02-09", "2019-02-14"
"SUV", "Harvey Dent", 302 600 2001, "2019-02-11", "2019-02-15"
In my main class I have a parseVehicleLine method like this..
private void parseReservationLine(String str){
Scanner sc = new Scanner(str);
sc.useDelimiter(",");
while(sc.hasNext()){
vehicleType = sc.next();//there is an error here because it is still an enum of Vehicle class
String cName = sc.next();
long phoneNumber = sc.nextLong();
String Date = sc.next();
String eDate = sc.next();
}
sc.close();
}
public abstract class Vehicle {
public enum VehicleType
{
ECONOMY(18.00), PREMIUM(22.50), SUV(25.50);
private double vehicleDailyCost;
private VehicleType(double vehicleDailyCost)
{
this.vehicleDailyCost = vehicleDailyCost;
}
public double getVehicleDailyCost()
{
return vehicleDailyCost;
}
}
Can someone explain how I could properly convert the VehicleType enum to a String without issues? Thanks!
You are reading the text file as String, so I think you need to convert String to VehicleType, not vice-versa as you mentioned.
You should be able to get enum from String using valueOf():
vehicleType = VehicleType.valueOf(sc.next());

Error Reading Files to Store their Data in an Array

The program that I am writing is in Java. I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
public String toString()
{
String str = firstname+" "+lastname;
return str;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "null."
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
Is the value of peoplearray[0] supposed to be null?
If not, what can I do to fix this problem?
Thanks!
The order of your arguments is wrong:
StringTokenizer token = new StringTokenizer("!", a);
According to API constructor
public StringTokenizer(String str, String delim)
use
StringTokenizer token = new StringTokenizer(a,"!");

Variable not in scope (I think), but not sure how to fix it

What I am doing is just practicing for a test and I thought it was doing just fine, but I am getting, what I think is a scope problem. It says, "teams cannot be resolved to a variable type" and I've tried a few things I thought would fix it, but they didn't work. Here is the code:
import java.util.Scanner;
public class fundamentalsofgame {
public String hteam;
public String cteam;
public String teams(String hometeam, String compteam){
String hteam = hometeam;
String cteam = compteam;
return "The teams are " + hteam + " vs " + cteam;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String hometeam;
String awayteam = "New England Cheatriots";
hometeam = scanner.next();
teams team = new teams(hometeam, awayteam); //error
}
}
teams is a method and not your class name instead it is fundamentalsofgame. So you need to make object of fundamentalsofgame and call teams method on it. Change this:
teams team = new teams(hometeam, awayteam); //error
to
fundamentalsofgame obj = new fundamentalsofgame();
fundamentalsofgame.teams(hometeam, awayteam);

Read data from a text file and create an object

I need some help:
I'm making a Supermarket simulation on Java, but I've got one problem, I have a text file (Stock.txt) where I have all the supermarket stock on it for example:
0-Bakery-Chocolate Cake-$12.5-250
1-Meat-Premium Steak-$2.6-120
2-Seafood-Tuna - $1.2-14
...
Where the first number is the "id" for the product, next is the department the product belongs, third is the name of the product, the next thing is the price, and the last number is how much pieces of the product the stock has.
I have this class:
public class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
}
So, basically what I need to do is to read each line from the text file and create the product, i.e. for the first line make something like this:
Product product1 = new Product(0,"Bakery","Chocolate Cake", 12.5, 250);
And then add it to an array
Product[0] = product1;
For all the things that are in the text file, then, when running the simulation each costumer will buy a random quantity of random products in stock, so the stock number will decrease. Finally, when the simulation ends, the program must write in the same text file, the modify quantity of each product.
The thing is that maybe it's too easy to do but I have no idea of how to do this, because reading and writing a file in Java has been a real problem for me since I started programming in Java (I'm a beginner).
I have some ideas of using the BufferedReader and the StringTokenizer classes for the reading and creating the object problems, but I can't figure it out how to do it, and I have no idea of how must I do the overwritting problem.
I'd really appreciate your help!
Oh! By the way, I really need to use only the arrays, so using an ArrayList or any other structure it's not even a choice :(
This is a good job for a Scanner to read in the data. As far as not being able to use collections like ArrayList you'll have to dynamically reallocate an array yourself.
Try the following:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("Stock.txt"));
input.useDelimiter("-|\n");
Product[] products = new Product[0];
while(input.hasNext()) {
int id = input.nextInt();
String department = input.next();
String name = input.next();
double price = Double.valueOf(input.next().substring(1));
int stock = input.nextInt();
Product newProduct = new Product(name, price, department, id, stock);
products = addProduct(products, newProduct);
}
for (Product product : products) {
System.out.println(product);
}
}
private static Product[] addProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProducts;
}
public static class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String n, double p, String d, int i, int s) {
name = n;
price = p;
department = d;
id = i;
stock = s;
}
#Override
public String toString() {
return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n",
id, department, name, formatter.format(price), stock);
}
}
Results:
ID: 0
Department: Bakery
Name: Chocolate Cake
Price: 12.50
Stock: 250
ID: 1
Department: Meat
Name: Premium Steak
Price: 2.60
Stock: 120
ID: 2
Department: Seafood
Name: Tuna
Price: 1.20
Stock: 14
For simplicity, I have defined all the items as String.
Product DAO:
public class Product {
private String name;
private String price;
private String department;
private String id;
private String stock;
//generate `enter code here`
//getters & setters
//toString
Put your product list in "testData/product.txt". This is assuming that your list of products comes in same format, i.e. id-department-name-price-stock \n.
Use the jUnit test below to test your code. You can certainly modify how you read the product.txt file (may be other powerful string readers).
#Test
public void test() {
try {
List<String> productLines = Files.readAllLines(java.nio.file.Paths.get("./testData/product.txt"), StandardCharsets.UTF_8);
for (String line: productLines)
Product product = new Product();
String[] tokens = line.split("-");
product.setId(tokens[0]);
product.setDepartment(tokens[1]);
product.setName(tokens[2]);
product.setPrice(tokens[3]);
product.setStock(tokens[4]);
System.out.println(product.toString())
}
} catch (IOException e) {
e.printStackTrace();
}
}
For future readers.
I had double quotes surrounding my csv (comma separated values) file.
And had some doubles and ints.
I also has going nuts trying to find a "bad line" and the value that was barfing.... in the csv file. Thus my exception with a decent message.
My "delimiter" is a comma and carriage return. And I deal with the double quotes "at the column level".
Here is what I came up with.
/* I know, a java example with the imports listed out ! shocking !! */
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
private void loadFromFile() {
Collection<MyCustomObject> items = new ArrayList<MyCustomObject>();
int lineNumber = 0;
String nextValue = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("MyFile.txt").getFile());
Scanner input = new Scanner(file)
.useDelimiter(",|\\R")
.useLocale(Locale.ENGLISH);
;
/* skip the header */
input.nextLine();
while (input.hasNext()) {
lineNumber++;
nextValue = input.next().replace("\"", "");
String zipCodeValue =nextValue;
nextValue = input.next().replace("\"", "");
String city = nextValue;
nextValue = input.next().replace("\"", "");
String usaState = nextValue;
nextValue = input.next().replace("\"", "");
double latitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
double longitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
int population = Integer.valueOf(nextValue);
items.add(new MyCustomObject(zipCodeValue, city, usaState, latitude, longitude, population));
}
} catch (Exception ex) {
throw new RuntimeException(String.format("Line number '%s, nextValue '%s''", lineNumber, nextValue), ex);
}
}
Sample text (csv) file:
"ZIPCODE","CITY","STATE","LATITUDE","LONGITUDE","POPULATION"
"06778","NORTHFIELD","CT",41.707,-73.105,555
"06779","OAKVILLE","CT",41.595,-73.081,777
"06782","PLYMOUTH","CT",41.657,-73.041,888

Categories