Buenas, estoy intentando realizar un ejercicio pero no logro sacarlo, la idea es leer los datos de un fichero en java y luego almacenarlo en una lista de objetos. El enunciado del ejercicio es el siguiente y el código que tengo yo hecho es el siguiente:
Realiza un programa que lea los datos del ejercicio 4. Para ello creará una lista de objetos de tipo Vehiculo. El programa irá almacenando en la lista los objetos leídos desde el archivo de texto "vehículos.txt". Una vez cargados todos los datos en la lista, ordena los vehículos por Marca y muestra el resultado por consola.
public class Ejercicio7 {
public static void main(String[] args) {
String idFichero = "vehiculos.txt";
String linea;
ArrayList<Vehiculo>lista=new ArrayList<>();
System.out.println("Leyendo el fichero: " + idFichero);
try (Scanner datosFichero = new Scanner(new File(idFichero))) {
while (datosFichero.hasNextLine()) {
linea = datosFichero.nextLine();
lista.add(linea);
for (int i = 0; i < lista.size(); i++) {
System.out.println(lista.get(i));
}
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
Gracias de antemano
No pones demasiada informacion y se hace mas dificil poder guiarte, pero suponiendo que tienes ya una clase "Vehiculo" serializable con sus atributos incluidos, solo tendrias que leer el objeto serializado usando un ObjectInputStream
public Object ReadObjectFromFile(String filepath)
{
try
{
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
Object obj = objectIn.readObject();
System.out.println("The Object has been read from the file");
objectIn.close();
return obj;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
Fuentes:
https://examples.javacodegeeks.com/core-java/io/file/how-to-read-an-object-from-file-in-java/
http://www.javapractices.com/topic/TopicAction.do?Id=57
https://stackoverflow.com/questions/30413227/how-to-read-and-write-an-object-to-a-text-file-in-java
Saludos
Cita de: LuisCardenas123 en 30 Abril 2019, 16:32 PM
Buenas, estoy intentando realizar un ejercicio pero no logro sacarlo, la idea es leer los datos de un fichero en java y luego almacenarlo en una lista de objetos. El enunciado del ejercicio es el siguiente y el código que tengo yo hecho es el siguiente:
Realiza un programa que lea los datos del ejercicio 4. Para ello creará una lista de objetos de tipo Vehiculo. El programa irá almacenando en la lista los objetos leídos desde el archivo de texto "vehículos.txt". Una vez cargados todos los datos en la lista, ordena los vehículos por Marca y muestra el resultado por consola.
public class Ejercicio7 {
public static void main(String[] args) {
String idFichero = "vehiculos.txt";
String linea;
ArrayList<Vehiculo>lista=new ArrayList<>();
System.out.println("Leyendo el fichero: " + idFichero);
try (Scanner datosFichero = new Scanner(new File(idFichero))) {
while (datosFichero.hasNextLine()) {
linea = datosFichero.nextLine();
lista.add(linea);
for (int i = 0; i < lista.size(); i++) {
System.out.println(lista.get(i));
}
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
Gracias de antemano
Que tal, como esta diseñado el fichero ? * Use aqui fluent api
* Tiene JFileChooser, al ejecutar lo usas para importar el .txt
Usonew ILeerVehiculos.LeerVehiculoImpl<>()
.buscarFichero()
.procesarFichero()
.ordenarPorMarca()
.make();
/**
*
* @param <T>
*/
@FunctionalInterface
public interface IBuilder<T> extends ShowData {
T make();
}
Bean Vehiculopackage com.foro.leerfichero;
import java.util.Objects;
import java.util.function.Consumer;
/**
* @implSpec THREAD-SAFE
* Bean Vehiculo
*/
public final class Vehiculo {
private final String marca;
private final String modelo;
public Vehiculo(final Vehiculo.Builder vb) {
this.marca = vb.marca;
this.modelo = vb.modelo;
}
public String getMarca() {
return marca;
}
public String getModelo() {
return modelo;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Vehiculo)) return false;
Vehiculo vehiculo = (Vehiculo) o;
return Objects.equals(marca, vehiculo.marca) &&
Objects.equals(modelo, vehiculo.modelo);
}
@Override
public int hashCode() {
return Objects.hash(marca, modelo);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Marca: ").append(marca);
sb.append(" Modelo: ").append(modelo).append("\n");
return sb.toString();
}
/**
* Builder
*/
public static class Builder implements IBuilder<Vehiculo> {
private String marca;
private String modelo;
public Builder con(final Consumer<Builder> consumer) {
consumer.accept(this);
return this;
}
@Override
public Vehiculo make() {
return new Vehiculo(this);
}
}
}
package com.foro.leerfichero;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
/**
* @autor rub'n
*/
public interface ILeerVehiculos {
interface Builder<T> {
/**
* Busca el fichero por medio del JFileChooser
* @return
*/
Builder<T> buscarFichero();
/**
*
* @return leer el fichero
*/
Builder<T> procesarFichero();
/**
*
* @return ordenar por la marca
*/
Builder<T> ordenarPorMarca();
/**
* Mutador
* @return
*/
T make();
}
@SuppressWarnings("unchecked")
public abstract class AbtractBaseClass<T> implements Builder<T> {
private final List<Vehiculo> vehiculoList = new ArrayList<>();
private List<String> datosLeidos = new ArrayList<>();
private Path pathFichero;
public AbtractBaseClass() {
}
@Override
public Builder<T> buscarFichero() {
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("archivo .txt","txt"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
final int opc = fileChooser.showOpenDialog(null);
if(opc == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(null,"No ha seleccionado fichero");
System.exit(0);
}
this.pathFichero =fileChooser.getSelectedFile().toPath().toAbsolutePath();
return this;
}
@Override
public Builder<T> procesarFichero() {
if(Objects.nonNull(pathFichero)) {
try (final BufferedReader br = Files.newBufferedReader(pathFichero, Charset.defaultCharset())) {
datosLeidos = br.lines()
.map(e -> e.replaceAll("\\s+", "-")) //flag
.filter(e -> !e.startsWith("Marca") && !e.isEmpty()) // ignorar la primera linea
.collect(Collectors.toList()); // convertimos en lista de Strings
datosLeidos
.forEach(e -> {
String marca = e.split("-")[0];
String modelo = e.split("-")[1];
final Vehiculo vehiculo = new Vehiculo.Builder()
.con(param -> {
param.marca = marca;
param.modelo = modelo;
})
.make();
vehiculoList.add(vehiculo);
});
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,"Path nullo");
}
return this;
}
@Override
public Builder<T> ordenarPorMarca() {
vehiculoList
.stream()
.sorted(Comparator.comparing(Vehiculo::getMarca)) // ordenamos en base a la marca
.forEach(System.out::println); //salida
return this;
}
}
/**
*
* @param <T>
*/
public class LeerVehiculoImpl<T> extends AbtractBaseClass<LeerVehiculoImpl> {
@Override
public LeerVehiculoImpl make() {
return new LeerVehiculoImpl();
}
}
public static void main(String ...blablabla) {
new ILeerVehiculos.LeerVehiculoImpl<>()
.buscarFichero()
.procesarFichero()
.ordenarPorMarca()
.make();
}
}
Posible fichero Vehiculos.txt
Marca Modelo
Bugati Chiron
Maserati Quattroporte
Suzuki Baleno
Lamborghini Huracan
OutPut por consolaMarca: Bugati Modelo: Chiron
Marca: Lamborghini Modelo: Huracan
Marca: Maserati Modelo: Quattroporte
Marca: Suzuki Modelo: Baleno
Process finished with exit code 0
Versión con ObjectInputStream y ObjectOuputStream, aquí los Bean a escribir deben implementar a Serializable
package archivos;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import beans.Persona;
/**
*
*
*/
public class ConObjectIOStream implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1513236979625800662L;
/**
*
*/
public ConObjectIOStream() {
//writeToFile();
writePersonToTempFile();
final List<Persona> listaPersona = readFromFile();
/**
* Ordenar por nombres alfabeticamente
*/
listaPersona
.stream()
.sorted(Comparator.comparing(Persona::getNombre))
.forEach(System.out::println);
}
private List<Persona> readFromFile() {
final List<Persona> listaPersona = new CopyOnWriteArrayList<>();
final Path pathAlimento = Paths.get("resources/temporal.tmp");
try(final BufferedInputStream bin = new BufferedInputStream(Files.newInputStream(pathAlimento));
final ObjectInputStream ob = new ObjectInputStream(bin)) {
while(Boolean.TRUE) {
synchronized (this) { //en caso de que readFrom se invoque desde un Thread()
final Object object = ob.readObject();
if(object instanceof Persona) {
listaPersona.add((Persona)object);
}
}
}
} catch (IOException | ClassNotFoundException e) {
//no hacer nada EOFException
}
return Collections.unmodifiableList(listaPersona);
}
private void writePersonToTempFile() {
final Persona persona1 = new Persona();
persona1.setNombre("Rubn");
persona1.setApellido("la muerte");
persona1.setCorreo("rdjfjfjjf@gmail.com");
persona1.setEdad(30);
final Persona persona2 = new Persona();
persona2.setNombre("Aaaaa");
persona2.setApellido("Espia");
persona2.setCorreo("fffffffp@gmail.com");
persona2.setEdad(27);
final Persona persona3 = new Persona();
persona3.setNombre("malware");
persona3.setApellido("wannacry");
persona3.setCorreo("testbma a@gmail.com");
persona3.setEdad(27);
final Path pathTem = Paths.get("resources/temporal.tmp");
try( final BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(pathTem, StandardOpenOption.CREATE));
final ObjectOutputStream ob = new ObjectOutputStream(bos)) {
synchronized (this) {
ob.writeObject(persona1);
ob.writeObject(persona2);
ob.writeObject(persona3);
}
}catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ConObjectIOStream();
}