Programas sobre ficheros
Programas para tratar ficheros: leer, escribir, ver sus propiedades, etc.
Descarga de todos los ejercicios: ficheros_unidad7
Leer el contenido de un fichero:
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class EjemploFichero01 {
// debe existir el fichero malaga.txt y estar situado en la misma carpeta que el este programa para poder leerlo
public static final String FICHERO = "malaga.txt";
public static void main(String[] args) {
BufferedReader br = null;
String linea = "";
try {
br = new BufferedReader(new FileReader(FICHERO));
while (linea != null) {
System.out.println(linea);
linea = br.readLine();
}
} catch (FileNotFoundException fnfe) { // qué hacer si no se encuentra el fichero
System.out.println("No se encuentra el fichero malaga.txt: " + fnfe.getMessage());
} catch (IOException ioe) { // qué hacer si hay un error en la lectura del fichero
System.out.println("No se puede leer el fichero: " + ioe.getMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException ex) {
System.out.println("Error al cerrar el fichero: " + ex.getMessage());
}
}
}
}
Fichero malaga.txt
un ejemplo de fichero málaga es muy bonita y tiene playa
Escribir en un fichero:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class EjemploFichero02 {
public static final String FICHERO = "fruta.txt";
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(FICHERO));
// Para añadir el texto al final del fichero, usamos otro constructor
//BufferedWriter bw = new BufferedWriter(new FileWriter(FICHERO, true));
bw.write("naranja\n");
bw.write("mango\n");
bw.write("chirimoya\n");
bw.flush();
bw.close();
System.out.println("Texto añadido al fichero: " + FICHERO);
} catch (IOException ioe) {
System.out.println("No se ha podido escribir en el fichero: " + ioe.getMessage());
}
}
}
Combinar el contenido de dos ficheros en uno nuevo:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* Ejemplo de uso de la clase File para mezclar dos ficheros
*
* @author Luis José Sánchez
*/
class EjemploFichero03 {
public static void main(String[] args) {
try {
BufferedReader br1 = new BufferedReader(new FileReader("fichero1.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("fichero2.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("mezcla.txt"));
String linea1 = "";
String linea2 = "";
while ((linea1 != null) || (linea2 != null)) {
linea1 = br1.readLine();
linea2 = br2.readLine();
if (linea1 != null) {
bw.write(linea1 + "\n");
}
if (linea2 != null) {
bw.write(linea2 + "\n");
}
}
br1.close();
br2.close();
bw.close();
System.out.println("Archivo mezcla.txt creado satisfactoriamente.");
} catch (IOException ioe) {
System.out.println("Se ha producido un error de lectura/escritura");
System.err.println(ioe.getMessage());
}
}
}
Ver las propiedades de los ficheros y carpetas en el directorio actual:
import java.io.File;
/**
* Ejemplo de uso de la clase File: Listado de los archivos del directorio actual
*
* @author Luis José Sánchez
*/
class EjemploFichero04 {
public static void main(String[] args) {
File f = new File("."); // se indica la ruta entre comillas
// el punto (.) es el directorio actual
String[] listaArchivos = f.list();
// for (int i = 0; i < listaArchivos.length; i ++) {
// System.out.println(listaArchivos[i]);
// }
// System.out.println("__________________________");
for (String nombreArchivo : listaArchivos) {
// System.out.println(nombreArchivo);
File fichero = new File(nombreArchivo);
if (fichero.isFile()) {
System.out.println("Fichero: " + nombreArchivo + "____" + fichero.length());
} else {
System.out.println("Carpeta: " + nombreArchivo);
}
}
}
}
Leer del fichero dato.txt un número n y almacenar en el fichero primos.dat todos los números primos entre 2 y n:
Seudocódigo:
- Crear previamente el archivo dato.txt con un número entero
- Leer el archivo
- Convertir el texto leído a un número entero n
- Realizar un bucle de i desde 2 hasta n
Calcular si i es primo
Si i es primo, guardarlo en el archivo
- Cerrar los flujos a los archivos de lectura y escritura
Fichero dato.txt
100
Código:
/**
* 1. Escribe un programa que guarde en un fichero con nombre primos.dat
* los números primos que hay entre 2 y el número leído en dato.txt.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class EjemploFichero05 {
public static final String LECTURA = "dato.txt";
public static final String ESCRITURA = "primos.dat";
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
int numero;
try {
// leer el número del fichero
br = new BufferedReader(new FileReader(LECTURA));
numero =Integer.parseInt(br.readLine());
// calcular los números primos y escribirlos en el fichero
bw = new BufferedWriter(new FileWriter(ESCRITURA));
for (int i = 2; i <= numero; i ++) {
if (esPrimo(i)) {
bw.write(String.valueOf(i) + "\n");
}
}
System.out.println("Números primos escritos en el fichero: " + ESCRITURA);
} catch (NumberFormatException nfe){
System.out.println("Error al convertir el número leído del fichero: " + nfe.getMessage());
} catch (IOException ioe) {
System.out.println("Error de lectura/escritura en un fichero: " + ioe.getMessage());
} finally {
try {
if (br != null)
br.close();
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error al cerrar el flujo: " + e.getMessage());
}
}
}
// Devuelve verdadero si el número que se pasa como parámetro es primo y falso en caso contrario.
public static boolean esPrimo(int x) {
boolean primo = true;
for (int i = 2; i <= Math.sqrt(x) && primo; i ++) {
if ((x % i) == 0) {
primo = false;
}
}
return primo;
}
}
Obtener los nombres y tamaños de los archivos situados en la misma carpeta del programa y en las subcarpetas existentes:
import java.io.File;
class EjemploFichero06 {
public static void main(String[] args) {
long tamano;
String mensaje;
File carpeta = new File("."); // se indica la ruta entre comillas
// el punto (.) es el directorio actual
String[] listaArchivos = carpeta.list();
for (String nombreArchivo : listaArchivos) {
File subcarpeta = new File(nombreArchivo);
mensaje = nombreArchivo;
if (subcarpeta.isFile()) {
tamano= subcarpeta.length();
mensaje += ", " + tamano + " bytes";
}
System.out.println(mensaje);
if (subcarpeta.isDirectory()) {
String[] listaSubcarpeta = subcarpeta.list();
for (String lista : listaSubcarpeta) {
System.out.println("\t" + lista);
}
}
}
}
}
Escribir objetos en un fichero:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serial1 {
public static final String SALIDA = "personas.dat";
public static void main(String[] args) {
FileOutputStream fos = null;
ObjectOutputStream salida = null;
Persona p;
try {
//Se crea el fichero
fos = new FileOutputStream(SALIDA);
salida = new ObjectOutputStream(fos);
//Se crea el primer objeto Persona
p = new Persona("12345678A","Lucas González", 30);
//Se escribe el objeto en el fichero
salida.writeObject(p);
//Se crea el segundo objeto Persona
p = new Persona("98765432B","Anacleto Jiménez", 28);
//Se escribe el objeto en el fichero
salida.writeObject(p);
//Se crea el tercer objeto Persona
p = new Persona("78234212Z","María Zapata", 35);
//Se escribe el objeto en el fichero
salida.writeObject(p);
System.out.println("Fichero creado: " + SALIDA);
} catch (FileNotFoundException e) {
System.out.println("FNFException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
} finally {
try {
// if(fos!=null) fos.close();
if (salida != null)
salida.close();
} catch (IOException e) {
System.out.println("IOException: "+e.getMessage());
}
}
}
}
Leer objetos de un fichero:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Serial2 {
public static final String ENTRADA = "personas.dat";
public static void main(String[] args) {
FileInputStream fis = null;
ObjectInputStream entrada = null;
Persona p;
try {
fis = new FileInputStream(ENTRADA);
entrada = new ObjectInputStream(fis);
while (fis.available() > 0) { // check if the file stream is at the end
p = (Persona) entrada.readObject();
System.out.println(p.getNif() + ", " + p.getNombre() + ", " + p.getEdad());
}
/*
p = (Persona) entrada.readObject(); //es necesario el casting
System.out.println(p.getNif() + ", " + p.getNombre() + ", " + p.getEdad());
p = (Persona) entrada.readObject();
System.out.println(p.getNif() + ", " + p.getNombre() + ", " + p.getEdad());
p = (Persona) entrada.readObject();
System.out.println(p.getNif() + ", " + p.getNombre() + ", " + p.getEdad());
*/
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
// if (fis != null) fis.close();
if (entrada != null) {
entrada.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.