Foros del Web » Programación para mayores de 30 ;) » Java »

JAVA Guardar en TXT y ReInsertar Objetos de 1 Clase

Estas en el tema de JAVA Guardar en TXT y ReInsertar Objetos de 1 Clase en el foro de Java en Foros del Web. Hola, podríais indicarme como guardar en un TXT los datos en JAVA y reinsertarlos, o donde podría encontrar el método? Se trata de un programa ...
  #1 (permalink)  
Antiguo 09/02/2017, 02:20
Avatar de 123
123
 
Fecha de Ingreso: junio-2001
Mensajes: 141
Antigüedad: 22 años, 10 meses
Puntos: 0
JAVA Guardar en TXT y ReInsertar Objetos de 1 Clase

Hola, podríais indicarme como guardar en un TXT los datos en JAVA y reinsertarlos, o donde podría encontrar el método?
Se trata de un programa de JAVA Local (no es web, etc). Una base de datos sencilla (1 clase con varios atributos):
- Con un formulario para insertar y modificar datos manualmente
- Que debería guardar todos los objetos de la clase (en formato tabla separada por tabuladores) en 1 archivo TXT para no perderlos al salir
- Y al volver a ejecutar el programa, leer el TXT y reinsertar todos los objetos con todos sus atributos en la clase

He buscado muchísimo, pero siempre lo basan a que los datos se inserten desde dentro del código (no desde el TXT). Como en la muestra que incluyo
Como se puede pasar TODOS los objetos de la clase Customer al BufferedWriter independientemente de que sean 5 o 50.000 customers, pero sin que estén en el código como abajo
customers[0] = new Customer("John JC", "Smith", 21);
customers[1] = new Customer("Saly MC", "Smith", 30);

Gracias


Código:
import java.io.*;
import javax.swing.JOptionPane;


public class SaveTxt{
	public static void infoBox(String infoMessage, String titleBar){
	    JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
	}
	public static void main(String[] args){
		// Create an array of type Customer
		Customer[] customers = getCustomers();
		// PrintWriter is used to write characters to a file in this situation
		PrintWriter custOutput = createFile("customers.txt");
		// infoBox("Creado customers.txt", "Creado customers.txt");
		// Enhanced for loop for arrays
		// Cycles through all of the people in the customers array
		for(Customer person : customers){	
			createCustomers(person, custOutput);	
		}
		// Closes the connection to the PrintWriter
		custOutput.close();
		// infoBox("Insertados customers.txt", "Insertados customers.txt");
		getFileInfo("customers.txt");
	}
    
	// class that defines all the fields for my customers
	private static class Customer{
		public String firstName, lastName;
		public int custAge;
		// constructor that's called when a customer is made
		public Customer(String firstName, String lastName, int custAge){
			this.firstName = firstName;
			this.lastName = lastName;
			this.custAge = custAge;
		}
	}
	
	// Creates an array of Customer Objects
	private static Customer[] getCustomers(){
		Customer[] customers = new Customer[5];
		customers[0] = new Customer("John JC", "Smith", 21);
		customers[1] = new Customer("Saly MC", "Smith", 30);
		customers[2] = new Customer("Paul KR", "Ryan", 21);
		customers[3] = new Customer("Mark", "Jacobs", 21);
		customers[4] = new Customer("Steve", "Nash", 21);
		return customers;
	}
	
	// Create the file and the PrintWriter that will write to the file
	private static PrintWriter createFile(String fileName){
		try{
			// Creates a File object that allows you to work with files on the hardrive
			File listOfNames = new File(fileName);
			// FileWriter is used to write streams of characters to a file
			// BufferedWriter gathers a bunch of characters and then writes
			// them all at one time (Speeds up the Program)
			// PrintWriter is used to write characters to the console, file
			PrintWriter infoToWrite = new PrintWriter(
			new BufferedWriter(
					new FileWriter(listOfNames)));
			return infoToWrite;
		}
		// You have to catch this when you call FileWriter
		catch(IOException e){
			System.out.println("An I/O Error Occurred");
			infoBox("I/O Error [" + fileName + "]", "I/O Error");
			// Closes the program
			System.exit(0);
		}
		return null;
	}
	
	// Create a string with the customer info and write it to the file
	private static void createCustomers(Customer customer, PrintWriter custOutput){
		// Create the String that contains the customer info
		String custInfo = customer.firstName + "\t" + customer.lastName + "\t";
		custInfo += Integer.toString(customer.custAge);
		// Writes the string to the file
		custOutput.println(custInfo);
	}
	
	// Read info from the file and write it to the screen
	private static void getFileInfo(String fileName){
		System.out.println("Info Written to File\n");
		// Open a new connection to the file
		File listOfNames = new File(fileName);
		try {
			// FileReader reads character files
			// BufferedReader reads as many characters as possible
			BufferedReader getInfo = new BufferedReader(
					new FileReader(listOfNames));
			// Reads a whole line from the file and saves it in a String
			String custInfo = getInfo.readLine();
			// readLine returns null when the end of the file is reached
			while(custInfo != null){
				// System.out.println(custInfo);
				// Break lines into pieces
				String[] indivCustData = custInfo.split("\t");
				// Convert the String into an integer with parseInt
				// int custAge = Integer.parseInt(indivCustData[2]);
				// System.out.print(indivCustData[0] + "\t" + indivCustData[1] + "\t" + custAge +"\n");
				System.out.print(indivCustData[0] + "\t" + indivCustData[1] + "\t" + indivCustData[2] +"\n");
				custInfo = getInfo.readLine();
			}
		}
		// Can be thrown by FileReader
		catch (FileNotFoundException e) {
			System.out.println("Couldn't Find the File");
			infoBox("Archivo NO Encontrado\n[" + fileName + "]", "Archivo NO Encontrado");
			System.exit(0);
		}
		catch(IOException e){
			System.out.println("An I/O Error Occurred");
			infoBox("I/O Error [" + fileName + "]", "I/O Error");
			System.exit(0);
		}
	}
}

Etiquetas: txt
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:03.