Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I wrote a program that creates 3 files with .txt format and writes some data's into them.
Now I am asked to define a value object for these files, And override the toString method, And then when I read the files Set them in to Value objects.
Now I'm completely confused and do not know where to start.
Thank you in advance for your help
If you want to create objects from text files first what are you going to do is read the file. There are many available classes in the Java API that can be used to read files: BufferedReader, FileReader etc.
The number of objects you will create will depend on the number of lines in the file. For example if you have a file with the following content
PersonName1,PersonSurname1,20
PersonName2,PersonSurname2,22
PersonName3,PersonSurname3,23
Let's say that these lines represent name, surname, and age of some users
What you need to do first is create a class that will represent this object, as we see in the text file the object will contain three parameters , so you create a class with three atribbutes
public class Person {
private String name;
private String surname;
private Integer age;
public Person(String name, String surname, Integer age) {
this.name = name;
this.surname = surname;
this.age = age;
}
#Override
public String toString() {
return "NAME : " + name + " : " + surname;
}
Now comes the reading part , for reading the file we will use BufferedReader, we read every line of the file by splitting the line by commas(,) for every iteration
String [] parameters = line.split(",");
This array of String now will represent our user attributes so we access it
String name = parameters[0];
String surname = parameters[1];
Integer age = Integer.parseInt(parameters[2]);
And now we create an object of Person every iteration and we add it to the list
Person p = new Person(name,surname,age);
list.add(p);
Example
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
List<Person> list = new ArrayList<>();
String line = null;
while((line = bufferedReader.readLine())!=null){
try {
String[] parameters = line.split(",");
if(parameters.length == 3) {
String name = parameters[0];
String surname = parameters[1];
Integer age = Integer.parseInt(parameters[2]);
Person p = new Person(name, surname, age);
list.add(p);
}
}catch (NumberFormatException e){
}
}
System.out.println("Object created from the file");
list.stream().forEach(System.out::println);
OUTPUT
NAME : PersonName1 : PersonSurname1
NAME : PersonName2 : PersonSurname2
NAME : PersonName3 : PersonSurname3
Related
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
I am new to Java Spring boot and I am trying to read data from a CSV file and then pass this data to my UI via REST.
I am using OpenCSV to parse my file. Here is my sample line in my file
firstname, lastname, card details.
card details consists of card number and expiry date. So my example text looks like:
joe, keller, 123456 22-2-1999.
The output from my rest end point should be:
{
"firstname": "joe",
"lastname" : "keller",
"card number" : "123456",
"expiry date" : 22-2-1999
}
I currently read the file using CsvToBeanBuilder and I seem to get stuck with mapping the final line to two different items.
Because the last column contains 2 fields - card number and expiry date, you cannot directly use CsvToBeanBuilder to read CSV file and convert it to your POJO. A alternative way is shown as follows:
First, I assume that you have already a POJO looks like:
class CreditCardInfo {
private String firstname;
private String lastname;
private String cardNumber;
private String expiryDate;
//general getters and setters
//toString()
}
Then you can use CSVReader.readNext() to read each line into a string array. And for the 3-rd column in CSV file you can separate it into 2 fields by empty space(" "): "123456" and "22-2-1999" with String.trim() for ignoring leading space. Therefore, you can store these fields to cardNumber and expiryDate of the POJO CreditCardInfo, respectively.
Code snippet
try (
Reader reader = Files.newBufferedReader(Paths.get("So58792579.csv"));
CSVReader csvReader = new CSVReader(reader);
) {
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
CreditCardInfo creditCardInfo = new CreditCardInfo();
creditCardInfo.setFirstname(nextRecord[0]);
creditCardInfo.setLastname(nextRecord[1].trim()); //trim() for ignoring leading space
creditCardInfo.setCardNumber(nextRecord[2].trim().split(" ")[0]);
creditCardInfo.setExpiryDate(nextRecord[2].trim().split(" ")[1]);
System.out.println(creditCardInfo.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
Console output
CreditCardInfo [firstname=joe, lastname=keller, cardNumber=123456, expiryDate=22-2-1999]
I have a txt document where each line is an independent message. This may include name, date of birth, address, etc. In addition to the address, all other information is in a row. Their order is not fixed. Name and birthday must be available, other information may not be available. If there is no name or birthday, this person should be ignored. Different people use blank lines to distinguish them. I want to read this information and put them in the arraylist, but I have no idea how to write the code.
My initial idea was to use a loop to read the content and store it, and if there was a blank line, start saving another content. But how to implement the code specifically I have no idea.
public class InforProcessor {
private File recordFile;
private File instructionFile;
private File outputFile;
private InforList inforlist;
public InforProcessor(String[]s)
{
recordFile = new File(s[0]);
instructionFile = new File(s[1]);
outputFile = new File(s[2]);
inforlist = new InforList();
}
}
This is my existing code, I want to read the contents of the recordFile and write to the arraylist.
Input file is like:
name john
birthday 11-11-2015
Address 11 Harry St, montain, TRY
birthday 12-25-2017
name peter
Postcode 2005
name jane
birthday 25-19-1998
Address 25 jeoje St, Sky, FLY
Postcode 1998
name geoge
The output information or useful information should be:
name john
birthday 11-11-2015
Address 11 Harry St, montain, TRY
birthday 12-25-2017
name peter
Postcode 2005
name jane
birthday 25-19-1998
Address 25 jeoje St, Sky, FLY
The last information should be delete because it do not have birthday.
First,you need to read all line from file,and every message splited by empty line.
Second,iterate over the message and check the messag is valid or not,if the message is valid then add the message to list.
private static List<String> filterFile(final String input) throws Exception {
List<String> result = new ArrayList<>();
List<String> lines = FileUtils.readLines(new File(input), "UTF-8");
System.out.println(lines.size());
int begin = 0;
int end = 0;
for (; end < lines.size(); end++) {
if (Strings.isNullOrEmpty(lines.get(end))) {
if (isValidInfo(lines, begin, end)) {
result.addAll(lines.subList(begin, end + 1));
}
begin = end + 1;
}
}
return result;
}
if message has name and birthday,the message is we want.
private static boolean isValidInfo(List<String> infos, int begin, int end) {
int counts = 0;
for (int i = begin; i < end; i++) {
String line = infos.get(i);
if (line.startsWith("name")) {
counts++;
}
if (line.startsWith("birthday")) {
counts++;
}
}
return counts == 2;
}
I am doing a reading text file practice where I read and store the data into a string array object. One ArrayList data should have photo, title, website, and date. The text file looks like this:
photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app-
actions-how-to-use-them.html
date:16-09-2018
I am trying to split and store them into a string array, which is an instance of my object class:
private List<ItemObjects> itemList;
and this is the constructor of my object class:
public ItemObjects(String photo, String name, String link, String date) {
this.photo = photo;
this.name = name;
this.link = link;
this.date = date;
}
I tried this but the ":" separator doesnt separate it like I want it to:
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
String[] tmpItemArr = sItems.split("\\:");
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
}
}
What is the best way of doing this? I have tried using for loop which stops at third line and adds the next one as new data. There are several online ways of doing it but some are very complicated and I am having trouble understanding it.
The problem is your understanding of using both the split function and the BufferReader.
By using readline function you are reading only one line so your split will split the first line only, you need to read the 4 first lines then add the item.
int count = 0;
String[] tmpItemArr = new String[4];
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
tmpItemArr[count] = sItems.split(":")[1];
count++;
if (count > 3) {
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
count = 0;
}
}
}
I have 3 csv files as follows:
Author file with columns: emailID | firstname | lastname
Books file with columns: title | isbn | author_email | description
Magazine with file Columns: title | isbn | author_email | releasedate
I need to display:
Based on the ISBN display all books and magazines
All books and magazines by an author
All books and magazines by title
I am using BufferedReader as of now:
String csvFileToRead = "csvFiles/authors.csv";
BufferedReader br = null;
String line = "";
String splitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] book = line.split(splitBy);
System.out.println("BOOKS [Email Address= " + book[0] + " , firstname="
+ book[1] + " , lastname=" + book[2] + "]");
}
}
I am confused about how to proceed with multiple files. Here are the approaches that i have considered:
Change
String csvFileToRead
to a String array
String[] csvFileToRead = {"data/authors.csv", "data/books.csv", "data/magazines.csv"};
Then pass each index each time to a method returning all rows but getting stuck with DS to use. I think ArrayList won't suffice since i need separated data.
Should I use a 2D array?
Do I need to read and store data in a DS in order to achieve the goal?
Should I make 3 different classes with getters and setters for authors, book and magazine?
What is the ideal way to do this? Please suggest.
I would create 3 List<String[]> each containing the matrix from one CSV file with a method like:
public List<string[]> csvToList(String csvFileToRead){
BufferedReader br = null;
String line = "";
String splitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
List<string[]> list_csv = new ArrayList<string[]>();
while ((line = br.readLine()) != null) {
String[] book = line.split(splitBy);
authors.add(book);
}
catch(Exception ex) {}
return list_csv;
}
And after that you can use it as :
List<String[]> authors = csvToList("csvFiles/authors.csv");
List<String[]> books = csvToList("csvFiles/books.csv");
List<String[]> magazine = csvToList("csvFiles/magazine.csv");
You can now print all what you want, for example the first case : Based on the ISBN display all books and magazines :
public void printISBN(string ISBN){
for(String[] s_tab in books)
if(s_tab[1].equals(ISBN))
System.out.println(s_tab[0]);
for(String[] s_tab in magazine)
if(s_tab[1].equals(ISBN))
System.out.println(s_tab[0]);
}
Hope I helped.
Edit
You could also create 3 classes for each files and do the same with Lists of thoses classes : List<Authors> List<Books> List<Magazine> but it is not necessary if you just have to answer those 3 questions.
One simple solution is to create three classes corresponding to your entities:
public class Author {
private String email;
private String firstName;
private String lastName;
// ...
}
public class Book {
private String title;
private String isbn;
private String authorEmail;
private String description;
// ...
}
public class Magazine {
private String title;
private String isbn;
private String authorEmail;
private Date releaseDate;
// ...
}
In your main code, when reading your CSV files you can fill a HashMap that maps an ISBN to a book, and a similar one for magazines, which you can use to retrieve a book or magazine by ISBN:
Map<String, Book> isbnBookMap = new HashMap<String, Book>();
Book book = isbnBookMap.get(isbn);
Map<String, Magazime> isbnMagazineMap = new HashMap<String, Magazime>();
Magazime magazine = isbnMagazineMap.get(isbn);
Similarly for getting a book or magazine by title.
As for getting books by author, you would need to map the author mail address to a List of Books since an author can have multiple books:
Map<String, List<Book>> authorBookMap = new HashMap<String, List<Book>>();
List<Book> books = authorBookMap.get(authorAddress);
You could use a Java CSV API
like OpenCSV