Manejo de archivos txt

peraltajavier
07 de Enero del 2009
Buenos dias a todos, quiero hacer la siguiente tarea leer un archivo de texto y despues mostrarlo por pantalla.

yo hago lo siguiente:

archivo = new File ("C:\archivo.txt");
fr = new FileReader (archivo);
BufferedReader br = new BufferedReader(fr);

de esta forma leo el archivo si no me equivoco, ahora el tema es como lo muestro por pantalla?

Gracias

fd
07 de Enero del 2009
df

mava
07 de Enero del 2009
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.*;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.ImageIcon;
import java.util.zip.*;
import javax.swing.plaf.metal.*;
import java.io.*;
import java.applet.*;
import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
import java.sql.DriverManager;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.util.Date;
import java.util.GregorianCalendar;

public class Librosprestados {

private static JLabel etiqueta, horaL, lugarL, actividadL;
private static JTextField horaT, lugarT;

private static JTextArea actividadT;

private static String dias[] = {"Lunes","Martes","Miércoles","Jueves","Viernes","Sábado","Domingo"};
private static String di[] = {"Lun","Mar","Mie","Jue","Vie","Sab","Dom"};
private static String meses[] = {"ENERO","FEBRERO","MARZO","ABRIL","MAYO","JUNIO","JULIO","AGOSTO","SEPTIEMBRE","OCTUBRE","NOVIEMBRE","DICIEMBRE"};
private static String meses2[] = {"Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Set","Oct","Nov","Dic"};
public static String datoSeleccionado = "";
private static String dia="";
private static String mes="";
private static String año="";
private static int months[] = {31,28,31,30,31,30,31,31,30,31,30,31}; // Cantidad maxima de los dias de cada mes
private static int anoActual = 0;
private static int mesActual = 0;
private static int diaActual = 0;
private static int anoTemporal = 0;
private static int mesTemporal = 0;
private static int cantidadArchivos = 1;
private static int buffer = 2048;
private static int contador=0;

public Librosprestados()
{
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.DAY_OF_MONTH);
datoSeleccionado=""+h;
RecuerdodelDia();
crearRecordatorioInterfaz();
}

public void establecerFechaActual() { // Obtiene del sistema la fecha actual

String fechaTotal = String.valueOf(new Date());

anoActual = Integer.parseInt(fechaTotal.substring(fechaTotal.length() - 4, fechaTotal.length()));

diaActual = Integer.parseInt(fechaTotal.substring(8,10));

anoTemporal = anoActual;
mesTemporal = mesActual;

}

public void fechaActual() { // Muestra en la tabla el mes actual

anoTemporal = anoActual;
mesTemporal = mesActual;

}// fechaActual


public static synchronized void RecuerdodelDia()
{
verRecordatorio();
}
public static synchronized void crearRecordatorioInterfaz() { // Muestra la interfaz para la opcion "Crear un recordatorio"
horaL = new JLabel("Hora:");
horaL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
lugarL = new JLabel("Lugar:");
lugarL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
actividadL = new JLabel("Actividad:");
actividadL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));

horaT = new JTextField(5);
horaT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
horaT.setBorder(BorderFactory.createLoweredBevelBorder());

lugarT = new JTextField(10);
lugarT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
lugarT.setBorder(BorderFactory.createLoweredBevelBorder());

actividadT = new JTextArea(10,35);
actividadT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
actividadT.setBorder(BorderFactory.createLoweredBevelBorder());


JPanel c1 = new JPanel(new GridLayout(2,1));
c1.add(horaL);
c1.add(horaT);

JPanel c2 = new JPanel(new GridLayout(2,1));
c2.add(lugarL);
c2.add(lugarT);

JPanel c3 = new JPanel(new BorderLayout(1,1));
c3.add(actividadL, BorderLayout.NORTH);
c3.add(new JScrollPane(actividadT), BorderLayout.SOUTH);

JPanel c4 = new JPanel(new BorderLayout(5,5));
c4.add(c1, BorderLayout.NORTH);
c4.add(c2, BorderLayout.CENTER);
c4.add(c3, BorderLayout.SOUTH);


JPanel c6 = new JPanel(new BorderLayout(5,5));
c6.add(c4, BorderLayout.NORTH);

JPanel c7 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c7.add(c6);



int respuesta = JOptionPane.showConfirmDialog(null,c7,"Mava Inc.",JOptionPane.YES_NO_OPTION);
if(respuesta == JOptionPane.YES_OPTION)
{
guardarRecordatorio(datoSeleccionado,"1","2009","!2:00","La Ceiba Honduras","Enamorar chicas");

}
}// crearRecordatorioInterfaz

public boolean espaciosLlenos() { // Retorna false si alguno de los espacios de Hora, Lugar y Actividad estan vacios

boolean retorno = false;

if(!horaT.getText().equals("") && !lugarT.getText().equals("") && !actividadT.getText().equals(""))
retorno = true;

return(retorno);

}// espaciosLlenos


public static synchronized void guardarRecordatorio(String Dia,String Mes, String Año,String Hora,String Lugar,String Actividad) { // Guarda en archivo lo que se escribio en los espacios de Hora, Lugar y Actividad

try {
cantidadArchivos = obtenerCantidad() + 1;
dia=Dia;
mes=Mes;
año=Año;
guardarCantidad();

String dat = "";
String filenametxt = String.valueOf("AgendaRecuerdo/Libros Prestados/Libros Prestados"+cantidadArchivos+".txt");
String filenamezip = String.valueOf("AgendaRecuerdo/Libros Prestados/Libros Prestados"+cantidadArchivos+".zip");
cantidadArchivos++;

dat += Dia + "n";
dat += String.valueOf(Mes) + "n";
dat += String.valueOf(Año) + "n";
dat += Hora + "n";
dat += Lugar + "n";
dat += Actividad + "n";

File archivo = new File(filenametxt);

FileWriter fw = new FileWriter(archivo);

BufferedWriter bw = new BufferedWriter(fw);

PrintWriter salida = new PrintWriter(bw);

salida.print(dat);
salida.close();

BufferedInputStream origin = null;

FileOutputStream dest = new FileOutputStream(filenamezip);

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

byte data[] = new byte[buffer];

File f = new File(filenametxt);

FileInputStream fi = new FileInputStream(f);

origin = new BufferedInputStream(fi, buffer);

ZipEntry entry = new ZipEntry(filenametxt);

out.putNextEntry(entry);

int count;

while((count = origin.read(data,0,buffer)) != -1)
out.write(data,0,count);

out.close();

}// try

catch(Exception e) {

JOptionPane.showMessageDialog(null,"Error en: "+e.toString(),"Error",JOptionPane.ERROR_MESSAGE);

}// catch

}// guardarRecordatorio

public static synchronized void guardarCantidad() { // Guarda en un archivo la cantidad de archivos con recordatorios que han sido generados

try {

String can = String.valueOf(cantidadArchivos);

File archivo = new File("AgendaRecuerdo/Libros Prestados/cantidadArchivos.txt");

FileWriter fw = new FileWriter(archivo);

BufferedWriter bw = new BufferedWriter(fw);

PrintWriter salida = new PrintWriter(bw);

salida.print(can);
salida.close();

BufferedInputStream origin = null;

FileOutputStream dest = new FileOutputStream("AgendaRecuerdo/Libros Prestados/cantidadArchivos.zip");

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

byte data[] = new byte[buffer];

File f = new File("AgendaRecuerdo/Libros Prestados/cantidadArchivos.txt");

FileInputStream fi = new FileInputStream(f);

origin = new BufferedInputStream(fi, buffer);

ZipEntry entry = new ZipEntry("AgendaRecuerdo/Libros Prestados/cantidadArchivos.txt");

out.putNextEntry(entry);

int count;

while((count = origin.read(data,0,buffer)) != -1)
out.write(data,0,count);

out.close();

}// try

catch(Exception e) {

JOptionPane.showMessageDialog(null,"Error en 1: "+e.toString(),"Error",JOptionPane.ERROR_MESSAGE);

}// catch

}// guardarCantidad

public static synchronized void verRecordatorio() { // Lee desde los archivos con recordatorios y extrae su informacion

try {
cantidadArchivos = obtenerCantidad() + 1;
String a =""+DATA.FECHA("/");
String a9[]=a.split("/");

boolean existe = false;

String filenametxt = "";
String filenamezip = "";
String hora = "";
String lugar = "";
String actividad = "";
String linea = "";

int dia = 0;
int mes = 0;
int ano = 0;

for(int i = 1; i < cantidadArchivos; i++) {

filenamezip = "AgendaRecuerdo/Libros Prestados/Libros Prestados"+i+".zip";
filenametxt = "AgendaRecuerdo/Libros Prestados/Libros Prestados"+i+".txt";

BufferedOutputStream dest = null;

BufferedInputStream is = null;

ZipEntry entry;

ZipFile zipfile = new ZipFile(filenamezip);

Enumeration e = zipfile.entries();

while(e.hasMoreElements()) {

entry = (ZipEntry) e.nextElement();

is = new BufferedInputStream(zipfile.getInputStream(entry));

int count;

byte data[] = new byte[buffer];

FileOutputStream fos = new FileOutputStream(entry.getName());

dest = new BufferedOutputStream(fos, buffer);

while((count = is.read(data,0,buffer)) != -1)
dest.write(data,0,count);

dest.flush();
dest.close();

is.close();

}// while

DataInputStream input = new DataInputStream(new FileInputStream(filenametxt));

dia = Integer.parseInt(input.readLine());
mes = Integer.parseInt(input.readLine());
ano = Integer.parseInt(input.readLine());
if(dia == Integer.parseInt(datoSeleccionado)) {

existe = true;

hora = input.readLine();
lugar = input.readLine();

while((linea = input.readLine()) != null)
actividad += linea + "n";

verRecordatorioInterfaz(hora,lugar,actividad);

hora = "";
lugar = "";
actividad = "";

}// if

input.close();

}// for
if(!existe)
{
String a1 =""+DATA.FECHA("/");
String a91[]=a1.split("/");
JOptionPane.showMessageDialog(null,"No existe ningun Libro Prestadon"+"para el "+datoSeleccionado+" de "+meses[mesTemporal].toLowerCase()+" del año "+a91[2],"No existe",JOptionPane.ERROR_MESSAGE,new ImageIcon("Iconos48X48/Symbol-Stop.png"));
}


}// try

catch(Exception e) {

String a1 =""+DATA.FECHA("/");
String a91[]=a1.split("/");
JOptionPane.showMessageDialog(null,"No se Permite Hacer esta Accion para hoyn"+" "+a91[0]+" de "+meses[mesTemporal].toLowerCase()+" del año "+a91[2],"El Sistema Lo hace Automatico Los Libro Prestado",JOptionPane.ERROR_MESSAGE,new ImageIcon("Iconos48X48/Symbol-Stop.png"));

}// catch
}// verRecordatorio

public static synchronized void verRecordatorioInterfaz(String h, String l, String a) { // Muestra la interfaz para la opcion "Ver un recordatorio"

horaL = new JLabel("Hora:");
horaL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
lugarL = new JLabel("Lugar:");
lugarL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
actividadL = new JLabel("Actividad:");
actividadL.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));

horaT = new JTextField(5);
horaT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
horaT.setBorder(BorderFactory.createLoweredBevelBorder());
horaT.setEditable(false);

lugarT = new JTextField(10);
lugarT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
lugarT.setBorder(BorderFactory.createLoweredBevelBorder());
lugarT.setEditable(false);

actividadT = new JTextArea(10,35);
actividadT.setFont(new Font("Constantia",Font.ITALIC+Font.BOLD,15));
actividadT.setBorder(BorderFactory.createLoweredBevelBorder());
actividadT.setEditable(false);


JPanel c1 = new JPanel(new GridLayout(2,1));
c1.add(horaL);
c1.add(horaT);

JPanel c2 = new JPanel(new GridLayout(2,1));
c2.add(lugarL);
c2.add(lugarT);

JPanel c3 = new JPanel(new BorderLayout(1,1));
c3.add(actividadL, BorderLayout.NORTH);
c3.add(new JScrollPane(actividadT), BorderLayout.SOUTH);

JPanel c4 = new JPanel(new BorderLayout(5,5));
c4.add(c1, BorderLayout.NORTH);
c4.add(c2, BorderLayout.CENTER);
c4.add(c3, BorderLayout.SOUTH);

JPanel c5 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c5.add(c4);
horaT.setText(h);
lugarT.setText(l);
actividadT.setText(a);

JOptionPane.showMessageDialog(null,c5,"Informacion Libros Prestados",JOptionPane.ERROR_MESSAGE,new ImageIcon("Iconos100X100/Document.png"));
}// verRecordatorioInterfaz

public static synchronized int obtenerCantidad() { // Lee desde el archivo cantidadArchivos.zip la cantidad de archivos que han sido generados

try {

BufferedOutputStream dest = null;

BufferedInputStream is = null;

ZipEntry entry;

ZipFile zipfile = new ZipFile("AgendaRecuerdo/Libros Prestados/cantidadArchivos.zip");

Enumeration e = zipfile.entries();

while(e.hasMoreElements()) {

entry = (ZipEntry) e.nextElement();

is = new BufferedInputStream(zipfile.getInputStream(entry));

int count;

byte data[] = new byte[buffer];

FileOutputStream fos = new FileOutputStream(entry.getName());

dest = new BufferedOutputStream(fos, buffer);

while((count = is.read(data,0,buffer)) != -1)
dest.write(data,0,count);

dest.flush();
dest.close();

is.close();

}// while

DataInputStream input = new DataInputStream(new FileInputStream("AgendaRecuerdo/Libros Prestados/cantidadArchivos.txt"));

int a = Integer.parseInt(input.readLine());

input.close();

return(a);

}// try

catch(Exception e) {

return(0);

}// catch

}// obtenerCantidad

public static void main(String args[]) {

Librosprestados cal = new Librosprestados();

}// main

}// class calendario
SOLO COPIALO Y EJECUTALO ES UN REGALO DE MAVA.INC SI NO SABES ME ESCRIBES AL [email protected] ESTOY PARA SERVIRLES ESTUDIO ING. DE SISTEMAS DE COMPUTACION

DarkCat
07 de Enero del 2009
LoL?

hbaranda
07 de Enero del 2009
Mira cuando tu serializa un archivo, lo haces con el objetivo de guardar en un txt una clase, luego en esa clase debe venir implementado un metodo que permita mostrar al ussuario todos los datos que esta clase tiene.

Ald0x
07 de Enero del 2009
Espero te sirva esto:

import java.io.*;

class leerArchivo {

public static void main(String args[]){

int c;

try {
FileInputStream f = new FileInputStream("leerArchivo.java");
while ((c = f.read()) != -1){
System.out.print((char)c);
}
}catch (IOException e){
System.out.println("Existe el archivo???");
}
}
}

j2m2h
07 de Enero del 2009
haces una comparacion entre
String s;
if (s=br.readLine != null){
System.out.println (""+s);}