Ejemplos de Código Java para Lectura y Escritura de Ficheros
Ejemplos de Métodos Java para el Manejo de Ficheros
Lectura y Escritura Secuencial
El siguiente método permite realizar operaciones de lectura y escritura de manera secuencial utilizando DataOutputStream y DataInputStream:
public static void lecturayescriturasecuencial()
{
DataOutputStream archivo = null;
DataInputStream fich = null;
String nombre = null;
int edad = 0;
try
{
archivo = new DataOutputStream(new FileOutputStream("C:\\Ejemplo\\secuencial.dat", true));
archivo.writeUTF("Cesar Alcantara Jorda ");
archivo.writeInt(25);
archivo.close();
} catch (IOException ex) {}
try
{
fich = new DataInputStream(new FileInputStream("C:\\Ejemplo\\secuencial.dat"));
while(fich.available() > 0)
{
nombre = fich.readUTF(); System.out.println(nombre);
edad = fich.readInt(); System.out.println(edad);
}
fich.close();
}
catch (IOException ex) {}
}Acceso Aleatorio y Visualización de Ficheros
Estos métodos permiten mostrar el contenido de un fichero y añadir datos utilizando acceso aleatorio con RandomAccessFile:
public static void mostrarFichero(RandomAccessFile fichero)
{
int n;
try
{
fichero.seek(0);
while (true)
{
n = fichero.readInt();
System.out.println(n);
}
} catch (EOFException e) { } catch (IOException ex) { }
}
public static void accesoAleatorio()
{
Scanner sc = new Scanner(System.in);
RandomAccessFile fichero = null;
int numero;
try
{
fichero = new RandomAccessFile("C:\\Ejemplo\\enteros.dat", "rw");
mostrarFichero(fichero);
System.out.println("Introduce un número entero para añadir al final"); numero = sc.nextInt();
fichero.seek(fichero.length());
fichero.writeInt(numero);
mostrarFichero(fichero);
} catch (IOException ex) { }
}Lectura con Buffer
Este método muestra cómo leer datos utilizando un búfer para optimizar el rendimiento al procesar archivos binarios, como imágenes:
public static void leerconbuffer()
{
int tama;
try
{
File f = new File("C:\\Ejemplo\\Foto.png");
FileInputStream flujoEntrada = new FileInputStream(f);
BufferedInputStream fEntradaConBuffer = new BufferedInputStream(flujoEntrada);
tama = fEntradaConBuffer.available();
System.out.println("Bytes disponibles: " + tama);
System.out.println("Leyendo 50 bytes...");
byte bytearray[] = new byte[50];
if (fEntradaConBuffer.read(bytearray) != 50)
System.out.println("No se pudieron leer 50 bytes");
System.out.println(new String(bytearray, 0, 50));
fEntradaConBuffer.close();
}
catch (IOException e) { }
}Copia de Ficheros
Método genérico para copiar el contenido de un archivo origen a un archivo destino utilizando bloques de bytes:
public static void copiarfichero(String origen, String destino)
{
try
{
OutputStream fsalida = new FileOutputStream(destino);
InputStream fentrada = new FileInputStream(origen);
byte []buffer = new byte[256];
while(true)
{
int n = fentrada.read(buffer);
if(n < 0) break;
fsalida.write(buffer, 0, n);
}
fsalida.close();
fentrada.close();
}
catch (IOException e) { }
}Lectura Estándar
Método para capturar la entrada estándar de texto carácter por carácter hasta encontrar un salto de línea:
public static void lecturaestandar()
{
StringBuilder str = new StringBuilder();
char c;
try
{
while((c = (char) System.in.read()) != '\n')
str.append(c);
}
catch (IOException ex) { }
System.out.println("Cadena introducida: " + str);
}