Writing class data to CSV , java - java

I am trying to write the data that I take in via the JOptionPane to a Csv file. Is there a way that I can just write the whole class to it rather than doing it individually?? Cant seem to get it to work
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AddStudent implements Serializable
{
public static void main(String[] args) throws IOException
{
Student s1 = new Student();
String id = JOptionPane.showInputDialog(null, "Enter Students ID ");
s1.setStudentName(JOptionPane.showInputDialog(null, "Enter Students name "));
s1.setStudentNumber(JOptionPane.showInputDialog(null, "Enter Students ID "));
s1.setStudentEmail(JOptionPane.showInputDialog(null, "Enter Students Email Address "));
s1.setStudentAdd(JOptionPane.showInputDialog(null, "Enter Students Home Address "));
String ProgID = JOptionPane.showInputDialog(null, "Enter the Programme code the student is taking ") ;
FileWriter fw = new FileWriter("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\ProgrammeID.csv", true);
}
FileOutputStream fos = new FileOutputStream("ProgrammeID");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student s1 = new Student();
oos.writeObject( s1);
oos.close();
}
And here is the Student Class
class Student
{
private String _studentNumber;
private String _studentName;
private String _studentAddress;
private String _studentEmail;
public void setStudentName(String studentName)
{
_studentName = studentName;
}
public void setStudentNumber(String studentNumber)
{
_studentNumber = studentNumber;
}
public void setStudentAdd(String studentAddress)
{
_studentAddress = studentAddress;
}
public void setStudentEmail(String studentEmail)
{
_studentEmail = studentEmail;
}
public String getNumber()
{
return _studentNumber;
}
public String getName()
{
return _studentName;
}
public String getAddress()
{
return _studentAddress;
}
public String getEmail()
{
return _studentAddress;
}
}

You need to override the method
toString()
It will be called automatically when handing the object of class Student to a method which requires a String.

You can create a JPanel for entering student information.
Like the following mock-up screen shot: ( Left side are the JLabel components, on right side, they are JTextField and JTextArea components )
Once the informaiton are entered, you can create a class to include these values and then write the value into CSV.
In this way, you can enter student informaiton, like name, ID, Email address etc, on one panel, rather than using JOptionPanel, you need to enter student information individually.

Related

Create and populate HashMap<Integer, ArrayList<object>>

I have an assignment for school that's all about using files, HashMap and ArrayList. This assignment requires 4 classes.
The first class is called FileReader and reads a txt file which is written line by line and each field that we need is separated by ";", for example ("Columbia University";"USA";78.86;2012). Each line contains 2 strings (university name and country) and 2 numbers (score and year). The FileReader class after reading the txt file returns its content in an arraylist.
The second class of the assignment is called UniversityScores and it has 4 fields (uniname, country, score, year), a constructor, accessor methods for all fields and a toString method.
The third class is the heart of our program. This class is called FileEditor and creates a Hashmap<Integer,ArrayList<UniversityScores>> where the key is the year field of each object and value I guess is the rest of the line. My problem is filling the right way the HashMap.
Also, my final 4th class is called FileWriter which creates a new txt and writes inside of it. All my classes work as supposed to except my FileEditor class. Any help needed. Thank you in advance!
Edit
I am supposed to write some other methods as well. For now my problem is the FileEditor class. I also posted the TestFiles class which contains the main function.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class FileReader{
private String fileName;
private Scanner scanner;
private File file;
private ArrayList<String> arrayList;
private String line;
public FileReader(String otherFileName){
this.fileName = otherFileName;
this.file = new File(fileName);
}
public boolean initReader(){
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("Just caught a FileNotFoundException.");
}
if(file.exists()){
return true;
}
else{
return false;
}
}
public ArrayList<String> readFile(){
this.arrayList = new ArrayList<String>();
while (scanner.hasNextLine()) {
this.line = scanner.nextLine();
arrayList.add(line);
}
arrayList.remove(0);
//System.out.println(arrayList);
return arrayList;
}
public void closeReader(){
scanner.close();
System.out.println("Scanner closed");
}
}
‌
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class FileWriter{
private String path;
private PrintWriter writer;
private File outputFile;
public FileWriter(String otherPath){
this.path = otherPath;
this.outputFile = new File(path);
}
public boolean initWriter(){
try{
writer = new PrintWriter(path);
}
catch (FileNotFoundException e){
System.out.println("just caught an exception");
}
if(outputFile.exists()){
return true;
}
else{
return false;
}
}
public void writeFile(){
writer.println("The first line");
writer.println("The second line");
writer.println("Christos");
}
public void closeWriter(){
writer.close();
System.out.println("Writer closed");
}
}
‌
class UniversityScore{
private String name;
private String country;
private double score;
private int year;
public UniversityScore(String otherName, String otherCountry, double otherScore, int otherYear){
this.name = otherName;
this.country = otherCountry;
this.score = otherScore;
this.year = otherYear;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public double getScore(){
return score;
}
public int getYear(){
return year;
}
public String toString(){
String outputString = name + "\t" + country + "\t" + score + "\t" + year;
return outputString;
}
}
‌
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class FileEditor{
private HashMap<Integer, ArrayList<UniversityScore>> scores = new HashMap<Integer, ArrayList<UniversityScore>>();
private ArrayList<String> lines;
public FileEditor(ArrayList<String> otherLines){
this.lines = otherLines;
}
public void fillHashMap(){
// that's where I need help
}
}
public class TestFiles {
public static void main(String[] args){
FileReader reader = new FileReader("universities.txt");
if(reader.initReader()){
FileEditor editor = new FileEditor(reader.readFile());
reader.closeReader();
editor.fillHashMap();
FileWriter writer = new FileWriter("universities_2015_output.txt");
if(writer.initWriter()){
writer.writeFile(editor.getScoresOfYear(2015));
writer.closeWriter();
}
else{
System.out.println("Error creating file");
}
System.out.println("Average university score of year 2015: "+editor.getAverageOfYear(2015));
System.out.println("Min university score of year 2015: "+editor.getMinOfYear(2015));
System.out.println("Max university score of year 2015: "+editor.getMaxOfYear(2015));
}
else{
System.out.println("Error opening file");
}
}
}
You will need a way to parse your lines into UniversityScore objects.
Now that you have all the scores, you can add it to your map, according to their year values (may be score but the type doesn't match nor makes practical sense), for example:
for(String line : lines){
String[] vals = line.split(";");
UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
if(scores.containsKey(score.getYear()){ // If the key exists
scores.get(score.getYear()).add(score);
}else{ // If the key doesn't exist, it must be created and added to the map
ArrayList<UniversityScore> newList = new ArrayList<>();
newList.add(score);
scores.put(score.getYear(), newList)
}
}
I noticed your map has an Integer key which corresponds to the year property of a score, so I assumed the map's keys are the years and not the scores as you suggested.
I didn't check if the code works, but it should at least give you an idea on how to fill your map.
It looks like you're being tasked with reading data from a file, and then generating some stats about the data in the file.
Currently, you're simply plopping each line in the ArrayList.
Looks like your next step is to go through each item in that list, and create a UniversityScore object. This is where you will have to parse each string into values that can be assigned to the various fields in the UniversityScore object. When you have done that, put the current line number (as an Integer key) and UniversityScore (as the value) in your HashMap.
Once you have done that, you will have to write the missing methods getScoresOfYear(Integer year), getAverageOfYear(int year), getMinOfYear(int year), and getMaxOfYear(int year) in the editor class.
try this:
public void fillHashMap() {
for(String line : lines) {
String [] fields = line.split(";");
UniversityScores us = new UniversityScores(fields[0], fields[1], fields[2], fields[3]);
if (scores.keySet().contains(us.getScore())) {
scores.get(us.getScore()).add(us);
}
else {
ArrayList<UniversityScores> t = new ArrayList<UniversityScores>();
t.add(us);
scores.put(us.getScore(), t);
}
}
}

How to Store Variable Data back from file in Java

Problem Defined: I store bookname and bookauthor variable data in file using tostring to buffer writer, When i run program next time program read the file but not to store data back to the variable
Please write read code and and variable data storing from file in JAVA
...........................................................................................................................................................
Three Classes One is Main Class,Second is filewriting class and One Class having book add function.Source Code is given here
import java.util.Scanner;
import java.io.*;
public class AddBook extends Filewriting{
public int add;
public AddBook(int add){this.add=add;}
public String bookname[] = new String[15];
public String bookauthor[] = new String[15];
public int price[] = new int[15];
public void addbook(){
for(int i=0;i<add;i++){
System.out.println("Enter the Book Title:");
Scanner input=new Scanner(System.in);
bookname[i]=input.nextLine();
System.out.println("Enter the Book Author:");
Scanner scan=new Scanner(System.in);
bookauthor[i]=input.nextLine();
System.out.println("Enter the Book Price:");
Scanner input1=new Scanner(System.in);
price[i]=input1.nextInt();
}
}
public String toString(int j)
{
return String.format("BookName:%s%nBookAuthor:%s%nBookPrice:%d%n%n................................................................................................................................%n",bookname[j],bookauthor[j],price[j]);
}
}
import java.util.*;
import java.io.*;
public class Filewriting {
public int add;
public void filewriting(){
System.out.println("How many Books you want to added:");
Scanner in=new Scanner(System.in);
add=in.nextInt();
try{
File file = new File("Hello1.txt");
// creates New file
file.createNewFile();
Writer writer = new FileWriter("Hello1.txt",true);
BufferedWriter bufferWriter = new BufferedWriter(writer);
AddBook obj=new AddBook(add);
obj.addbook();
for ( int i = 0; i < add; i++){
// bufferWriter.write(obj.bookname[i] + obj.bookauthor[i] +obj.price[i]);
bufferWriter.write(obj.toString(i));
}
bufferWriter.close();
}
catch(Exception e)
{
}
}
/* // Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close(); */
}
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]){
System.out.println("Enter 1 to Add Books:");
System.out.println("Enter 2 to Check Store Books again in Variable:");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
if(i==1){
System.out.println("You Press B");
Filewriting fw=new Filewriting();
fw.filewriting();
}
if(i==2)
{
Filewriting fw=new Filewriting();
AddBook obj=new AddBook(fw.add);
for ( int j = 0; j < 2; j++) // for storing 2 variables data
{
System.out.println(obj.bookname[j]); // just check bookname,shows null
}
}
// Please write code that we read the file as well as data is stored again in Variables
}
}
I see You can write Data in File as not well.From your Code it is impossible to Store data in your variables.You must set and get Methods in your program in order to store variables.Following Program Code is help you to storing file data to variable perfectly.
................................................................................
public class Book {
public String name;
public String author;
public int price;
public Book(){
this("","",0);
}
public Book(String name,String author,int price){
setName(name);
setAuthor(author);
setPrice(price);
}
public void setName(String name){
this.name= name ;
}
public void setAuthor(String author){
this.author = author ;
}
public void setPrice(int price){
this.price = price ;
}
public String getName(){
return name;
}
public String getAuthor(){
return author;
}
public int getPrice(){
return price;
}
}
import java.io.*;
import java.util.*;
public class ReadText {
Scanner input,a;
public void OpenBook(){
File f = new File("Hello1.txt");
if ( f.exists()){
System.out.println("Welcome Ur File IS Open....."+f);
}
else
{
System.out.println("Error... File DOes not exits");
System.exit(1);
}
try {
input = new Scanner(new File("Hello1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void ReadBook(){
Book b = new Book();
while((input.hasNext())){
b.setName(input.nextLine());
b.setAuthor(input.nextLine());
b.setPrice(Integer.parseInt(input.nextLine()));
System.out.printf("Book Name:%s\nBook Author:%s\nBook Price:%d\n",b.getName(),b.getAuthor(),b.getPrice());
}
}
}

CSV to tab delimited java in command line

Updated Code. This program should take the CSV file and separate it into TSV files by school,but I am not getting it to work. I am getting it to create the files correctly, but only one has any data in it...
public class Student implements Comparable<Student>{
public int id = 0;
public String name = "";
public String school = "";
public Student(int id, String name, String school){
this.id = id;
this.name = name;
this.school = school;
}
public String toString(){
return id+"\t"+name+"\t"+school;
}
#Override
public int compareTo(Student o) {
return this.school.compareTo(o.school);
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class ReadCSV {
public static String CSV_FILE_PATH = "/Users/eringray/Desktop/csvtotab/input.csv";
public static void main(String[] args){
try {
BufferedReader br = new BufferedReader(new FileReader(CSV_FILE_PATH));
BufferedWriter bw = new BufferedWriter(new FileWriter(CSV_FILE_PATH + ".tsv"));
ArrayList<Student> list = new ArrayList<Student>();
String line = "";
while((line = br.readLine()) != null) {
String[] values = line.split(",");
if(values.length == 3) {
String idAsString = values[0];
String name = values[1];
String school = values[2];
int id = Integer.parseInt(idAsString);
Student s = new Student(id, name, school);
list.add(s);
}
}
Collections.sort(list);
String currentSchool = "";
for(int i = 0; i < list.size(); i++){
Student stu = list.get(i);
if(currentSchool != stu.school){
currentSchool = stu.school;
bw = new BufferedWriter(new FileWriter(CSV_FILE_PATH + stu.school + ".tsv"));
}
String lineText = stu.toString();
bw.write(lineText);
bw.newLine();
}
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The first thing, you have to do is reading the input file.
I think, you need to read it line by line (depends on file structure).
https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
Next step is to seperate the data and sort it by school (if i understood your question well).
For this you have to split the data and create a class to store the information:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
public Class Student{
public String name = "";
....
public Student(String name, String school, ...){}
}
When you have created a Student object for each student in the list, you have to sort the students by school:
You could implement compareable and use Collection.sort().
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Last thing is to print the output, for this you have to override the toString method of the student class:
public String toString(){
return this.id+"\t"+this.name+"\t"+this.school;
}
and iterate throug the list of your students and call the toString method:
System.out.println(students.get(i).toString());
EDIT:
If you need the output in a file and not in the console, just use a fileoutputStream and a bufferedwriter to print the output of the toString method in a file.

Java Problems With Deserialization

I know that this question has been addressed before,but i simply cannot find the answer no matter how hard i try.
I am trying to serialize and deserialize objects in Java. I am having problems in the deserialization. I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848. Why do i get this instead of the actual values typed in?
Here is my code
package prueba;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prueba {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
File file = new File("f.txt");
List <Estudiantes> lista = new ArrayList<>();
boolean continuar = true;
while (continuar == true){
Estudiantes es = new Estudiantes();
System.out.println("Ingrese nombre");
Scanner kb = new Scanner(System.in);
es.nombre = kb.nextLine();
System.out.println("Ingrese Apellido");
Scanner kb1 = new Scanner(System.in);
es.apellido = kb1.nextLine();
System.out.println("Ingrese Número");
Scanner kb2 = new Scanner(System.in);
es.numero = kb2.nextInt();
lista.add(es);
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
for (Estudiantes est: lista){
output.writeObject(est);
}
output.close();
fo.close();
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
ArrayList<Estudiantes> est2 = new ArrayList<Estudiantes>();
try {
while (true){
Estudiantes s = (Estudiantes)input.readObject();
est2.add(s);
}
}
catch (EOFException ex){}
for (Estudiantes s :est2){
System.out.println(s);
fi.close();
input.close();
}
System.out.println("0 para salir; 1 para continuar");
Scanner kb3 = new Scanner(System.in);
int rev = kb3.nextInt();
if (rev == 0){
continuar = false;
System.out.println("Hasta Luego");
}
}
}
}
And here is my Estudiantes class
package prueba;
import java.io.Serializable;
public class Estudiantes implements Serializable{
String nombre, apellido;
int numero;
}
Thanks
I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848
That's what you get when you explicitly or implicitly call toString() on an object whose class hasn't overridden it.
It isn't evidence that you have a problem.
I think if you are getting the values like prueba.Estudiantes#1bd7848 you are its already been deserialized. You just have to override the toString() properly to get the output. Not sure if this helps
When you try to print your class when reading back the objects you previously wrote you have to implement the toString() method from the Object class here is what I mean.
Change your class to this:
public class Estudiantes implements Serializable {
private static final long serialVersionUID = 123L; // has to be unique
String nombre, apellido;
int numero;
#Override
public String toString() {
System.out.println("first name: " + nombre);
System.out.println("last name: " + apellido);
System.out.println(numero);
return // a string you want to print
}
}

Saving Linked List to file (Elements are incorrect)

I need to save the linked list I created to a file but I want each part of the users account to be its own element. i.e. (username, password, email, name, breed, gender, age, state, hobby). Something is wrong with my code however and each account is its own element. Any help would be great!
Also here is a link to my Account Class which is used to create the Linked List
http://pastebin.com/jnBrcnP1
Linked List looks like this:
tobi
tobi123
tobi#hotmail.com
tobi
Mixed Breed
Male
1-2
Virginia
Walking
peppy
peppy123
peppy#hotmail.com
peppy
Chihuahua
Male
5-6
Virginia
Eating
Saves to file like this:
tobitobi123tobi#hotmail.comtobiMixed BreedMale1-2VirginiaWalking
peppypeppy123peppy#hotmail.compeppyChihuahuaMale5-6VirginiaEating
Code for creating Linked List:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Main extends javax.swing.JFrame implements ActionListener{
public static String readLine(BufferedReader br) throws IOException {
String rl = br.readLine();
if (rl.trim().length() > 2){
return rl;
}else return readLine(br);
}
public static void main(String[] args) {
LinkedList<Account> account = new LinkedList<Account>();
try
{
read(account, "output.txt");
} catch (Exception e)
{
System.err.println(e.toString());
}
display(account);
}
public static void read(LinkedList<Account> account, String inputFileName) throws java.io.IOException
{
BufferedReader infile = new BufferedReader(new FileReader(inputFileName));
while(infile.ready())
{
String username = readLine(infile);
String password = readLine(infile);
String email = readLine(infile);
String name = readLine(infile);
String breed = readLine(infile);
String gender = readLine(infile);
String age = readLine(infile);
String state = readLine(infile);
String hobby = readLine(infile);
Account a = new Account(username, password, email, name, breed, gender, age, state, hobby);
account.add(a);
a.showList();
}
infile.close();
}
public static void display(LinkedList<?> c)
{
for (Object e : c)
{
System.out.println(e);
}
}
Code for Saving Linked List to file:
String file_name = "output.txt";
try {
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
ListIterator itr = account.listIterator();
while (itr.hasNext()) {
Account element = (Account) itr.next();
out.write("" + element);
out.newLine();
}
out.close();
System.out.println("File created successfully.");
} catch (Exception e) {
}
This is the problem, in Account:
public String toString() {
return ""+username+"\n"+password+"\n"+email+"\n"+name+
"\n"+breed+"\n"+gender+"\n"+age+"\n"+state+"\n"+hobby;
}
You're assuming that \n is the appropriate line ending. My guess is you're running on Windows, where it would be \r\n. Personally, I think it would be better for your "writing" code not to use toString() at all, but to write out the lines itself - after all, it knows the format it wants to use.
(Additionally, I would advise against using "" + ... as a way of converting a value into a string...)

Categories