Written by students who passed Immediately available after payment Read online or as PDF Wrong document? Swap it for free 4.6 TrustPilot
logo-home
Summary

Sumario ENTRADASALIDA Y MANEJO DE FICHEROS

Rating
-
Sold
-
Pages
52
Uploaded on
18-01-2026
Written in
2025/2026

PROGRAMACIÓN - ENTRADA/SALIDA Y MANEJO DE FICHEROS

Institution
Course

Content preview

📚 PROGRAMACIÓN -
ENTRADA/SALIDA Y MANEJO DE
FICHEROS

⚠️ Conceptos Trampa

ERROR #1: Confundir Streams de Bytes, Caracteres y Líneas


Los estudiantes mezclan clases y acaban usando FileReader para leer imágenes (FAIL) o
FileInputStream para archivos de texto (funciona pero está MAL).


TABLA COMPARATIVA :


Tipo de Cuándo Ejemplo de
Clase Método clave
dato usarla uso

Archivos
binarios:
Bytes (8 imágenes, Copiar un
FileInputStream read() → int
bits) vídeos, archivo .jpg
ejecutables,
PDFs

Caracteres Archivos de Leer un
FileReader (16 bits read() → int texto plano archivo de
Unicode) (.txt, .csv) configuración

Cuando
Leer un
Líneas necesitas
readLine() → fichero de
BufferedReader completas procesar
String log línea a
(String) línea por
línea
línea

Escribir Guardar una
Bytes
FileOutputStream write(int) datos imagen
(salida)
binarios procesada

, Tipo de Cuándo Ejemplo de
Clase Método clave
dato usarla uso

Caracteres Escribir Crear un
FileWriter write(String)
(salida) texto archivo .txt

Escribir
Generar un
Líneas (con write() + muchas
BufferedWriter informe con
búfer) newLine() líneas
10.000 líneas
(eficiente)

Escribir
Escribir logs
Líneas println() , texto con
PrintWriter con
formateadas printf() formato
timestamps
cómodo


EL TRUCO MENTAL:


1. ¿Es binario o texto? → Binario = InputStream/OutputStream, Texto =
Reader/Writer
2. ¿Necesito leer línea completa? → Sí = BufferedReader
3. ¿Necesito eficiencia con muchas operaciones? → Sí = Buffered (cualquiera)


EJEMPLO DEL ERROR TÍPICO:


// ❌ MAL - Usando FileInputStream para texto
FileInputStream in = new FileInputStream("carta.txt");
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c); // Funciona pero es INCORRECTO
}


// ✅ BIEN - Usando FileReader para texto
FileReader in = new FileReader("carta.txt");
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}


// ✅ MEJOR - Usando BufferedReader para texto (línea a línea)
BufferedReader in = new BufferedReader(new FileReader("carta.txt"));
String linea;

, while ((linea = in.readLine()) != null) {
System.out.println(linea);
}




ERROR #2: La Jerarquía de Excepciones (y el orden del catch)


Java obliga a que captures las excepciones de MÁS ESPECÍFICA a MÁS GENÉRICA. Si lo
haces al revés, ni siquiera compila.


JERARQUÍA COMPLETA:


Throwable (clase raíz)
├── Error (errores graves del sistema, NO captures estos)
│ ├── OutOfMemoryError
│ └── StackOverflowError

└── Exception (excepciones que SÍ debes capturar)
├── IOException (padre de las excepciones de E/S)
│ ├── FileNotFoundException
│ ├── EOFException
│ └── SocketException

├── RuntimeException (no verificadas)
│ ├── NullPointerException
│ ├── ArithmeticException
│ └── NumberFormatException

└── ClassNotFoundException




TABLA DE EXCEPCIONES EN E/S:


Excepción Cuándo se lanza Cómo prevenirla

Error genérico de Usar try-catch siempre
IOException
entrada/salida con operaciones de E/S

FileNotFoundException El archivo que intentas Comprobar con
abrir NO existe File.exists() antes de

, Excepción Cuándo se lanza Cómo prevenirla

abrir

Intentas leer más allá Usar un bucle que detecte
EOFException
del final del archivo el final ( read() == -1 )

Al deserializar, la clase Asegurarse de que la clase
ClassNotFoundException
del objeto no existe esté en el classpath


EJEMPLO DEL ERROR DE ORDEN:


// ❌ ERROR DE COMPILACIÓN - Orden incorrecto
try {
FileReader fr = new FileReader("noexiste.txt");
} catch (IOException e) { // ← Demasiado genérica primero
System.out.println("Error E/S");
} catch (FileNotFoundException e) { // ← ERROR: Unreachable code
System.out.println("Archivo no encontrado");
}


// ✅ CORRECTO - De específica a genérica
try {
FileReader fr = new FileReader("noexiste.txt");
} catch (FileNotFoundException e) { // ← Primero la específica
System.out.println("El archivo no existe");
} catch (IOException e) { // ← Luego la genérica
System.out.println("Error de E/S");
}




ERROR #3: DataStreams vs ObjectStreams


Ambos sirven para guardar datos, pero son COMPLETAMENTE DIFERENTES.


TABLA COMPARATIVA: FLUJOS DE DATOS VS OBJETOS

Written for

Course

Document information

Uploaded on
January 18, 2026
Number of pages
52
Written in
2025/2026
Type
SUMMARY

Subjects

$4.09
Get access to the full document:

Wrong document? Swap it for free Within 14 days of purchase and before downloading, you can choose a different document. You can simply spend the amount again.
Written by students who passed
Immediately available after payment
Read online or as PDF

Get to know the seller
Seller avatar
jesús6

Also available in package deal

Get to know the seller

Seller avatar
jesús6 Universidad Nacional de Educación a Distancia
Follow You need to be logged in order to follow users or courses
Sold
1
Member since
6 months
Number of followers
0
Documents
17
Last sold
5 months ago

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Working on your references?

Create accurate citations in APA, MLA and Harvard with our free citation generator.

Working on your references?

Frequently asked questions