I have a program in which I read a CSV file and export a text file type.
CSV attributes are name, date of birth, email and address.
I need a BufferedReader through a user can insert the email of one of the records and delete the entire row in the CSV (deleting name, date of birth, and email address) and re-export the text file type.
I do not have much knowledge of Java so much that could help me guide me to the solution.
I share the code,
Help is appreciated,
Thank you!
public class Personas {
private String nombre;
private String fechaNacimiento;
private String email;
private String direccion;
public Personas(String nombre, String fechaNacimiento, String email,
String direccion) {
super();
this.nombre = nombre;
this.fechaNacimiento = fechaNacimiento;
this.email = email;
this.direccion = direccion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
}
Here is the main class
import java.io.*;
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Personas[] miLista = new Personas[100];
int i = 0;
String texto = "";
FileReader lector;
try {
lector = new FileReader("C:\\Users\\CD\\Downloads\\dummydata.csv");
BufferedReader contenido=new BufferedReader(lector);
try {
while((texto=contenido.readLine())!=null){
String[] valores = texto.split(",");
Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
miLista[i]=persona;
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("hay mas de 100 registros en el archivo");
System.out.println("solo se cargaran los primeros 100");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.print("El archivo no se encuentra...");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
for (Personas persona : miLista) {
System.out.print(persona.getNombre());
System.out.print(persona.getDireccion());
System.out.print(persona.getFechaNacimiento());
System.out.println(persona.getEmail());
}
File miArchivo = new File("miNuevoArchivo.txt");
try{
FileWriter fw = new FileWriter(miArchivo);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter wr = new PrintWriter(bw);
for (Personas persona : miLista) {
wr.write(persona.getNombre()+"\t");
wr.append(persona.getFechaNacimiento()+"\t");
wr.append(persona.getDireccion()+"\t");
wr.println(persona.getEmail());
}
wr.close();
bw.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
I hope it help... but not sure it's what you want to do.
Try to not mix differents languages, see try-with-resource, use List (ArrayList) instead of Arrays, create simple functions and read some docs about iterator.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Principal {
private static final String IN = "C:\\Users\\CD\\Downloads\\dummydata.csv";
private static final String OUT = "C:\\Users\\CD\\Downloads\\result.txt";
public static List<Personas> readFile(final String file) throws Exception {
final List<Personas> result = new ArrayList<Personas>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String texto = "";
while ((texto = reader.readLine()) != null) {
final String[] valores = texto.split(",");
final Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
result.add(persona);
}
}
return result;
}
public static void write(final String file, final List<Personas> personas) throws Exception {
new File(file);
try (PrintWriter wr = new PrintWriter(new File(file))) {
for (final Personas persona : personas) {
wr.write(persona.getNombre() + "\t");
wr.append(persona.getFechaNacimiento() + "\t");
wr.append(persona.getDireccion() + "\t");
wr.println(persona.getEmail());
}
}
}
public static void main(final String[] args) throws Exception {
final List<String> emailsToRemove = Arrays.asList("email1#lol.com", "email2#lol.com");
final List<Personas> personas = readFile(IN);
//Remove some personnas
for (Iterator<Personas> it = personas.iterator(); it.hasNext(); /**RIEN**/) {
Personas act = it.next();
if(emailsToRemove.contains(act.getEmail())){
it.remove();
}
}
write(OUT, personas);
}
}
Related
public void loadFromFile() {
System.out.println("Loading books...");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream("books.txt");
Scanner sc = new Scanner(fileInput);
if (sc.hasNext()) {
System.out.format("%-5s %-45s %-10s", "Id", "Name", "Price");
System.out.println();
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} else {
System.out.println("(empty)");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("File not found");
} finally {
try {
fileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO: your code here
}
i have a .txt file with the requirement a program reads it and parses it into object. Each line is an object including attributes id, name and price
how can I parse text to object
public static final class Book {
private int id;
private String name;
private double price;
}
public static void main(String... args) throws FileNotFoundException {
List<Book> books = readMovies(new File("a.txt"));
}
private static List<Book> readMovies(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useLocale(Locale.ENGLISH);
List<Book> books = new ArrayList<>();
while (scan.hasNext()) {
Book book = new Book();
book.id = scan.nextInt();
String line = scan.nextLine().trim();
int pos = line.indexOf(" ");
book.name = line.substring(0, pos).trim();
book.price = Double.parseDouble(line.substring(pos + 1).trim());
books.add(book);
}
return books;
}
}
// this code can help you, happy to help
import java.io.*;
public class FileTextCheck {
public static void main(String[] args) {
User u1 = new User("Sudhakar", 27, "Male");
User u2 = new User("Richa", 25, "Female");
try {
FileOutputStream fos = new FileOutputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u1);
oos.writeObject(u2);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
User pr1 = (User) ois.readObject();
User pr2 = (User) ois.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
ois.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String gender;
User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}
}
You cannot parse any type of text to a java object. The text should be in JSON format. You can parse JSON string to java object using Gson library.
I need to find a way to split a csv file into multiple csv files based on the value of a particular column of my input csv file. I need the name of the newly generated csv files to be the value of that column as well.
For example:
input CSV file =
Col1,Col2,Col3
1,2,Cat
1,3,Cat
2,4,Dog
2,5,Dog
I want to split by Col3 so I get the following table and file name:
---------------- File name = Cat.csv
Col1,Col2,Col3
1,2,Cat
1,3,Cat
---------------- File name = Dog.csv
Col1,Col2,Col3
2,4,Dog
2,5,Dog
Any way to do this?
Thanks for any help.
So, far i can only do only reading file and saving in a object.
package com.jcg;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
private static final String COMMA_DELIMITER = ",";
private static final int ORDER_ID_IDX = 0;
private static final int ORDER_DATE_IDX = 1;
private static final int ORDER_COUNTRY_IDX = 2;
private static final int ORDER_VALUE = 3;
public static void readCsvFile(String fileName) {
BufferedReader fileReader = null;
try {
List<Order> orders = new ArrayList<Order>();
String line = "";
fileReader = new BufferedReader(new FileReader(fileName));
fileReader.readLine();
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
Order order = new Order(Long.parseLong(tokens[ORDER_ID_IDX]), tokens[ORDER_DATE_IDX],
tokens[ORDER_COUNTRY_IDX], tokens[ORDER_VALUE]);
orders.add(order);
}
}
for (Order order : orders) {
System.out.println(order.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
}
Order.java
package com.jcg;
public class Order {
private long id;
private String dates;
private String country;
private String values;
public Order(long id, String dates, String country, String values) {
super();
this.id = id;
this.dates = dates;
this.country = country;
this.values = values;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDates() {
return dates;
}
public void setDates(String dates) {
this.dates = dates;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getValues() {
return values;
}
public void setValues(String values) {
this.values = values;
}
#Override
public String toString() {
return "Order [id=" + id + ", dates=" + dates + ", country=" + country + ", values=" + values + "]";
}
}
Since you have list of Order
List<Order> orders = new ArrayList<Order>();
Do group by on list List<Order> orders with key as Col3 (which is private String values) and values as List<Order>
Map<String,List<Order>> result = orders.stream()
.collect(Collectors.groupingBy(Order::getValues));
Now for each entry in Map create .csv file with key and write write corresponding values to that file
result.forEach((key,value)->{
File newFile = new File(key+".csv");
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
values.forEach(order->{
StringBuilder builder = new StringBuilder();
builder.append(order.getId()+",");
builder.append(order.getDates()+",");
builder.append(order.getCountry()+",");
builder.append(order.getValues()+",");
writer.write(builder.toString());
writer.newLine();
};
writer.flush();
writer.close();
});
I need help with this code i can't get a good count with the relation
this is the class for map:
package primero;
// Generated 03-mar-2015 8:46:59 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Estudiantes generated by hbm2java
*/
public class Estudiantes implements java.io.Serializable {
private String dni;
private Estudiantes estudiantes;
private String nombre;
private String direccion;
private String poblacion;
private String telefono;
private Set<Estudiantes> estudianteses = new HashSet<Estudiantes>(0);
private Set<Cursos> cursoses = new HashSet<Cursos>(0);
public Estudiantes() {
}
public Estudiantes(String dni) {
this.dni = dni;
}
public Estudiantes(String dni, Estudiantes estudiantes, String nombre,
String direccion, String poblacion, String telefono,
Set<Estudiantes> estudianteses, Set<Cursos> cursoses) {
this.dni = dni;
this.estudiantes = estudiantes;
this.nombre = nombre;
this.direccion = direccion;
this.poblacion = poblacion;
this.telefono = telefono;
this.estudianteses = estudianteses;
this.cursoses = cursoses;
}
public String getDni() {
return this.dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public Estudiantes getEstudiantes() {
return this.estudiantes;
}
public void setEstudiantes(Estudiantes estudiantes) {
this.estudiantes = estudiantes;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getPoblacion() {
return this.poblacion;
}
public void setPoblacion(String poblacion) {
this.poblacion = poblacion;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Set<Estudiantes> getEstudianteses() {
return this.estudianteses;
}
public void setEstudianteses(Set<Estudiantes> estudianteses) {
this.estudianteses = estudianteses;
}
public Set<Cursos> getCursoses() {
return this.cursoses;
}
public void setCursoses(Set<Cursos> cursoses) {
this.cursoses = cursoses;
}
}
package primero;
// Generated 03-mar-2015 8:46:59 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Cursos generated by hbm2java
*/
public class Cursos implements java.io.Serializable {
private int codCurso;
private String nombre;
private String profesor1;
private String profesor2;
private String profesor3;
private Set<Estudiantes> estudianteses = new HashSet<Estudiantes>(0);
public Cursos() {
}
public Cursos(int codCurso) {
this.codCurso = codCurso;
}
public Cursos(int codCurso, String nombre, String profesor1,
String profesor2, String profesor3, Set<Estudiantes> estudianteses) {
this.codCurso = codCurso;
this.nombre = nombre;
this.profesor1 = profesor1;
this.profesor2 = profesor2;
this.profesor3 = profesor3;
this.estudianteses = estudianteses;
}
public int getCodCurso() {
return this.codCurso;
}
public void setCodCurso(int codCurso) {
this.codCurso = codCurso;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getProfesor1() {
return this.profesor1;
}
public void setProfesor1(String profesor1) {
this.profesor1 = profesor1;
}
public String getProfesor2() {
return this.profesor2;
}
public void setProfesor2(String profesor2) {
this.profesor2 = profesor2;
}
public String getProfesor3() {
return this.profesor3;
}
public void setProfesor3(String profesor3) {
this.profesor3 = profesor3;
}
public Set<Estudiantes> getEstudianteses() {
return this.estudianteses;
}
public void setEstudianteses(Set<Estudiantes> estudianteses) {
this.estudianteses = estudianteses;
}
}
this is the ejercise with the problem
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import primero.*;
public class Main {
public static void main(String[] args) {
//BufferedReader entrada=new BufferedReader(new InputStreamReader(System.in));
SessionFactory sesion = SessionFactoryUtil.getSessionFactory();
Session session = sesion.openSession();
//Transaction tx = session.beginTransaction();
try{
/*
System.out.println("Introduce el codigo del cliente: ");
short num=Short.parseShort(entrada.readLine());
System.out.println("\nDATOS DEL CLIENTE: "+num+"\n");
Clientes cliente = new Clientes();
cliente=(Clientes)session.load(Clientes.class, num);
*/
System.out.println("-------------------------------------------------------");
Estudiantes estu = new Estudiantes();
Query q = session.createQuery("from Estudiantes");
List <Estudiantes> lista = q.list();
Iterator <Estudiantes> iter = lista.iterator();
while(iter.hasNext()){
estu = iter.next();
System.out.println("Dni: "+estu.getDni()+", "+estu.getNombre());
System.out.println("Direccion: "+estu.getDireccion());
System.out.println("Representante: "+estu.getDni()+", "+estu.getNombre());
long count = (long) session.createQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
System.out.println("Numero de cursos: "+count);
//===============================================================
Cursos curs=new Cursos();
Query q1 = session.createQuery("from Cursos");
List <Cursos> lista1 = q1.list();
Iterator <Cursos> iter1 = lista1.iterator();
while(iter1.hasNext()){
curs = iter1.next();
System.out.println(" "+curs.getCodCurso()+" ==> "+curs.getNombre()+": "+curs.getProfesor1()+", "+curs.getProfesor2()+", "+curs.getProfesor3());
}
System.out.println("-------------------------------------------------------");
}
}
catch(ObjectNotFoundException e){
System.out.println("No existe el cliente");
//e.printStackTrace();
}
catch(NullPointerException e){
System.out.println("Los datos son nulos");
//e.printStackTrace();
}
catch(NumberFormatException e){
System.out.println("El numero introducido no es valido");
//e.printStackTrace();
}
//tx.commit();
session.close();
System.exit(0);
}
}
I can't print all the studients for the course. I need help. Thanks.
Set lines = new HashSet(10000); // maybe should be bigger
String line;
This following line should be changed from
long count = (long) session.createQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
to this
long count = (long) session.createSQlQuery("select count(*) from Cursos where estudianteses="+estu.getEstudianteses()).uniqueResult();
It has to be createSqlQuery()
I need to store an ArrayList of type "Comment" in my SharedPreferences. This is my model class:
public class Comment {
public String getPID() {
return PID;
}
public void setPID(String pID) {
PID = pID;
}
public String PID;
public String Comment;
public String Commenter;
public String Date;
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
public String getCommenter() {
return Commenter;
}
public void setCommenter(String commenter) {
Commenter = commenter;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
}
So my ArrayList contains 2 Comments that need to be stored in SharedPreferences. I tried HashSet but it requires String values:
ArrayList<Comment_FB> fb = getFeedback(); //my Comments List
SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0);
Editor editor = pref.edit();
Set<String> set = new HashSet<String>();
set.addAll(fb);
editor.putStringSet("key", set);
editor.commit();
How do I get this done folks? :)
I think you need to store it as a file.
public static boolean save(String key, Serializable obj) {
try {
FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key);
ObjectOutputStream objOutStream;
objOutStream = new ObjectOutputStream(outStream);
objOutStream.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static Object getObject(String key) {
Object obj = null;
if (!new File(instance.getCacheDir() + "/" + key).exists())
return obj;
FileInputStream inputStream;
try {
inputStream = new FileInputStream(instance.getCacheDir() + "/" + key);
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
obj = objInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
Your "Comment" class should implements Serializable.
I'm doing a small program an addressbook that allows the user to: add contact, search contact and delete contact. All of this data is read and written to .dat file.
Also, how would you create a layout in the data file, (i.e. name, lastname, address and number)?
I'm terrible at Java and I need to get this done.
My code:
public interface Inter
{
//Interface class
public void addContact();
public void deleteContact();
public void searchContact();
public void readFile();
}
public class Contact
{
static String name;
static String lastName;
static String address;
static String number;
public Contact () { }
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; // reads from dat file
import java.io.FileWriter; // writes from dat file
import java.io.IOException;
import java.io.InputStreamReader;
public class Phonebook extends Contact implements Inter
{
public static void main(String[] args)
{
} // main
#Override
public void deleteContact() { }
#Override
public void searchContact() { }
#Override
public void addContact()
{
String details = null;
System.out.println("Enter new contact i.e name:number:lastname ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try
{
details=in.readLine();
String[] tokens =details.split(":"); // eg david :098:Needham
name= tokens[0];
lastName = tokens[1];
address = tokens[2];
number = tokens[3];
} catch (IOException e1) { }
FileWriter fw = null; // writes contact info to the dat file
try
{
fw = new FileWriter("data.dat");
fw.write(name);
fw.write(lastName);
fw.write(address);
fw.write(number);
} catch (IOException e) { }
BufferedWriter bw = new BufferedWriter(fw);
}
public void readFile() // reads contacts from dat file
{
try
{
BufferedReader in = new BufferedReader(new FileReader("data.dat"));
String str;
while ((str = in.readLine()) != null)
{}
} catch(Exception ex) { }
}
}
Your file format should be a .csv, so it would look like:
name,lastname,address,number,
name,lastname,address,number,
name,lastname,address,number,
I know I shouldn't be posting code for you, but here:
class Contact {
public String name, lastname, address, number;
public Contact(String name, String lastname, String address, String number) {
this.name = name;
this.lastname = lastname;
this.address = address;
this.number = number;
}
public boolean equals(Contact c) {
if(name.equals(c.name) && lastname.equals(c.lastname)
&& address.equals(c.address) && number.equals(c.number))
return true;
return false;
}
public String toString() {
return name+","+lastname+","address+","+number+",";
}
}
public class ContactDriver {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public static void addContact(Contact c) {
contacts.add(c);
}
public static Contact deleteContact(Contact c) {
return contacts.remove(c);
}
public static int searchContact(Contact c) {
for(int i = 0; i < contacts.size(); i++)
if(contacts.get(i).equals(c))
return i;
return -1;
}
public static void readContacts(String file) throws Exception {
Scanner in = new Scanner(new File(file)).useDelimiter(",");
while(in.hasNextLine()) {
addContact(in.next(), in.next(), in.next(), in.next());
}
}
public static void writeContacts(String fileName) {
FileWriter dest = new FileWriter(fileName);
for(Contact c : contacts)
dest.write(c.toString());
}
public static void main() {
readContacts();
// Do logical stuffs
writeContacts();
}
}
That code is untested, so I'll edit anything that has an error.
Have fun learning more Java!