I wrote code and I can save same data in .csv file.
Now i want to read my data from csv file for example by UID.
I tried but can not get all my data by name.
Here is source
Pojo class code
public class Product {
private String UID;
private String name;
private String personalNumber;
#Override
public String toString() {
return "Product{" +
"UID='" + UID + '\'' +
", name='" + name + '\'' +
", personalNumber='" + personalNumber + '\'' +
", gender='" + gender + '\'' +
", issueState='" + issueState + '\'' +
", documentType='" + documentType + '\'' +
'}';
}
private String gender;
private String issueState;
private String documentType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public String getPersonalNumber() {
return personalNumber;
}
public void setPersonalNumber(String personalNumber) {
this.personalNumber = personalNumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIssueState() {
return issueState;
}
public void setIssueState(String issueState) {
this.issueState = issueState;
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
}
And here is a main java class
public class ReadFromFile {
public static void main(String[] args) throws Exception {
File file = new File("C:\\\\cardReaderID\\2017-08-31.csv");
Scanner input = new Scanner(file);
Product[] products = new Product[0];
while(input.hasNext()) {
String UID = input.next();
String name = input.next();
String personalNumber = input.next();
Product newProduct = new Product();
newProduct.setUID(UID);
newProduct.setName(name);
newProduct.setPersonalNumber(personalNumber);
}
for (Product product : products) {
System.err.println(product);
}
}
How I can read all my data from csv file by name? I mean, UID,fullname and etc.
How i can solve my problem?
Thanks everyone
Here is a solution
public class CSVReader {
public static void main(String[] args) {
String csvFile= "C:\\\\cardReaderID\\2017-08-31.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I have a text file like down below:
jack; 488;22;98
kylie; 541;72;81
jenna; 995;66;17 .
.
The list is formatted as follows:
On every line, the first number after the name is the student's code and the numbers following it are scores.
I want to pass the student's code (as a String) as the input to the program and it should return the student's second score to me.
I have tried bufferedreader ,but I can just write all text files as output, but I can't search for the code and the other things.
Thanks
BufferedReader br = new BufferedReader(new FileReader("filePath"));
String contentLine = br.readLine();
while (contentLine != null) {
String[] result=contentLine.split(";");
String studentCode =result[1].trim();
// apply your logic for studentCode here
contentLine = br.readLine();
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FilterCsv {
private class Student {
private String name;
private String code;
private String score;
private String score2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore2() {
return score2;
}
public void setScore2(String score2) {
this.score2 = score2;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", score='" + score + '\'' +
", score2='" + score2 + '\'' +
'}';
}
}
private Function<String, Student> mapToItem = (line) -> {
System.out.println(line);
String[] p = line.split(";");
Student student = new Student();
student.setName(p[0]);
if (p[1] != null && p[1].trim().length() > 0) {
student.setCode(p[1]);
}
if (p[2] != null && p[2].trim().length() > 0) {
student.setScore(p[2]);
}
if (p[3] != null && p[3].trim().length() > 0) {
student.setScore2(p[3]);
}
return student;
};
private List<Student> processInputFile(String inputFilePath, String name) {
List<Student> inputList = new ArrayList<>();
try {
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().map(mapToItem).collect(Collectors.toList());
br.close();
String secondScore = inputList
.stream()
.peek(System.out::println)
.filter((s -> s.getName().equals(name)))
.findFirst()
.get().getScore2();
System.out.println("Score 2 for " + name + " is: " + secondScore);
} catch (IOException e) {
System.out.println(e);
}
return inputList;
}
public static void main(String[] args) {
new FilterCsv().processInputFile("your filepath, "studentsName");
}
}
add some error checking and stuff...
Cheers
I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.
I'm trying to edit a player in my code and then update the values in my CSV file that I created but I am not sure about how to write the new values to the file itself. I know what I want to do but just not sure how about to do it. I am editing the amount paid and trying to update it in the file for the player.
Here are my classes:
Main class here
package squashapplication;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
System.out.println("Enter ID:");
int input = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
for(SquashPlayer id:theList){
if(id.getId() == input){
System.out.println("Enter in new amount paid:");
int newAmount = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
id.setAmountPaid(newAmount);
}
}
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
SquashPlayer class here
package squashapplication;
import java.util.Scanner;
/**
*
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
This might help,
Instead of fw.write, which I believe that's what you use, use fw.append adding a new line character "\n" at the end.
I've made an ArrayList of players that I want to search through to change the amount they have paid. I want to be able to enter in their ID, then be able to change their amount paid just for that player. I am also writing it to a CSV file but I am not sure how to update that file with the new value. I'm not sure about how to go about doing this.
What I want to do is just update a value in the ArrayList for a specific player based on player input on the registration ID, then I want to update that value in the file.
Here are my 3 classes that I have made: SquashPlayer
package squashapplication;
import java.util.Scanner;
/**
*
* #author Evan
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
Here is my main class:
package squashapplication;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
And here is where I store my scanner in FileUtility:
package squashapplication;
import java.util.Scanner;
public class FileUtility {
private static Scanner input = new Scanner(System.in);
public static Scanner getInput() {
return input;
}
}
My string is like this:
[{"trends":[{"name":"#Happy16thPoniGoyangLimitedEditionJKT48","url":"http:\/\/twitter.com\/search?q=%23Happy16thPoniGoyangLimitedEditionJKT48","promoted_content":null,"query":"%23Happy16thPoniGoyangLimitedEditionJKT48","events":null},{"name":"#SemihVAROLTAYFAileHaftaSonuTakibi","url":"http:\/\/twitter.com\/search?q=%23SemihVAROLTAYFAileHaftaSonuTakibi","promoted_content":null,"query":"%23SemihVAROLTAYFAileHaftaSonuTakibi","events":null},{"name":"#JeeveTeriJodi","url":"http:\/\/twitter.com\/search?q=%23JeeveTeriJodi","promoted_content":null,"query":"%23JeeveTeriJodi","events":null},{"name":"#Tolga\u00D6\u011F\u00FCt\u0130leTakiple\u015Fme","url":"http:\/\/twitter.com\/search?q=%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","promoted_content":null,"query":"%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","events":null},{"name":"#CNEnjoyMondayyy","url":"http:\/\/twitter.com\/search?q=%23CNEnjoyMondayyy","promoted_content":null,"query":"%23CNEnjoyMondayyy","events":null},{"name":"Medha Patkar","url":"http:\/\/twitter.com\/search?q=%22Medha+Patkar%22","promoted_content":null,"query":"%22Medha+Patkar%22","events":null},{"name":"Asaram Bapuji","url":"http:\/\/twitter.com\/search?q=%22Asaram+Bapuji%22","promoted_content":null,"query":"%22Asaram+Bapuji%22","events":null},{"name":"Tune Talk","url":"http:\/\/twitter.com\/search?q=%22Tune+Talk%22","promoted_content":null,"query":"%22Tune+Talk%22","events":null},{"name":"Golden Globes 2014","url":"http:\/\/twitter.com\/search?q=%22Golden+Globes+2014%22","promoted_content":null,"query":"%22Golden+Globes+2014%22","events":null},{"name":"Game of Thrones Season 4","url":"http:\/\/twitter.com\/search?q=%22Game+of+Thrones+Season+4%22","promoted_content":null,"query":"%22Game+of+Thrones+Season+4%22","events":null}],"as_of":"2014-01-13T09:59:22Z","created_at":"2014-01-13T09:07:24Z","locations":[{"name":"Worldwide","woeid":1}]}]
I can parse this json string when I remove "[" and "]" from first and last character by following code:
private TrendTags getTrendTagsJSON(String jsonString) {
TrendTags trendTags = null;
jsonString = jsonString.substring(1, jsonString.length()-1);
try {
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//convert json string to object
trendTags = objectMapper.readValue(jsonString, TrendTags.class);
System.out.println(trendTags);
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
return trendTags;
}
And my TrendsTag class is this:
public class TrendTags {
#JsonProperty("trends")
private Trend[] trend;
#JsonProperty("locations")
private TrendLocation[] trendLocation;
#Override
public String toString() {
return "TrendTags{" +
"trend=" + Arrays.toString(trend) +
", trendLocation=" + Arrays.toString(trendLocation) +
'}';
}
public Trend[] getTrend() {
return trend;
}
public void setTrend(Trend[] trend) {
this.trend = trend;
}
public TrendLocation[] getTrendLocation() {
return trendLocation;
}
public void setTrendLocation(TrendLocation[] trendLocation) {
this.trendLocation = trendLocation;
}
/************************
* Trend item class *
************************/
public static class Trend {
private String name;
private String url;
private String query;
#Override
public String toString() {
return "Trend {" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
/************************
* Trend location class *
************************/
public static class TrendLocation {
private String name;
private int woeid;
#Override
public String toString() {
return "TrendLocation{" +
"name='" + name + '\'' +
", woeid=" + woeid +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWoeid() {
return woeid;
}
public void setWoeid(int woeid) {
this.woeid = woeid;
}
}
}
Since I have one object in array so it's possible to remove "[" and "]" from first and last chatacter. But this is not the solution.
My question is how to parse the json string with "[" and "]" characters? There should be a simple solution but I cannot find it. Thanks
Your JSON represents an array of your TrendTags objects. You're attempting to parse it as if it represented a single TrendTags object.
Get rid of all that code trying to modify the JSON, and just do:
TrendTags[] trendTags =
objectMapper.readValue(jsonString, TrendTags[].class);
That said, using a List is generally better;
List<TrendTags> trendTags =
objectMapper.readValue(jsonString, new TypeReference<List<TrendTags>>(){});