Text files: write and read with Scanner · Archivos de texto: escribir y leer con Scanner
Reading and writing text files
- A text file stores text that stays on disk after the program ends.
- To read a file in Java we use a
Scannerconnected to aFile. - To write a file we use a
PrintWriter. In this lesson each program writes a file, then reads it back. - Bonus lesson: the AP CSA exam does not test file input/output. Learn this for real programs — you will not be examined on it.
Lectura y escritura de archivos de texto
- Un archivo de texto almacena texto que permanece en el disco después de que finaliza el programa.
- Para leer un archivo en Java usamos un
Scannerconectado a unFile. - Para escribir un archivo usamos un
PrintWriter. En esta lección, cada programa escribe un archivo y luego lo lee nuevamente. - Lección adicional: el examen AP CSA no evalúa la entrada/salida de archivos. Aprende esto para programas reales; no serás evaluado sobre ello.
Reading and writing a file · Leer y escribir un archivo
A file is used in three steps: open · abrir it, read or write lines, then close · cerrar it. · Un archivo se utiliza en tres pasos: abrirlo, leer o escribir líneas, luego cerrarlo.
The imports you need
- File tools live in two places, so we import both at the top.
import java.io.*;— forFile,PrintWriter, andIOException.import java.util.Scanner;— for theScannerreader.
Las importaciones que necesitas
- Las herramientas para archivos se encuentran en dos lugares, por lo que importamos ambas al principio.
import java.io.*;— paraFile,PrintWritereIOException.import java.util.Scanner;— para el lectorScanner.
import java.io.*;
import java.util.Scanner;
Files can fail, so we say throws IOException
- Reading or writing a file can go wrong (the file may be missing).
- Java makes you handle this. The simplest way is to add
throws IOExceptiontomain. - This says "if a file error happens, let the program stop". That is fine for these tasks.
Los archivos pueden fallar, así que declaramos throws IOException
- Leer o escribir un archivo puede tener problemas (el archivo podría no existir).
- Java te obliga a manejar esto. La forma más sencilla es agregar
throws IOExceptionamain. - Esto significa "si ocurre un error de archivo, deja que el programa se detenga". Eso está bien para estas tareas.
Writing a file with PrintWriter
new PrintWriter("data.txt")makes (or empties) a file calleddata.txt.- Use
writer.println(...)to write one line, just like printing to the screen. - Always call
writer.close()when you finish, so the text is saved.
Escribir un archivo con PrintWriter
new PrintWriter("data.txt")crea (o vacía) un archivo llamadodata.txt.- Usa
writer.println(...)para escribir una línea, igual que imprimir en pantalla. - Llama siempre a
writer.close()cuando termines, para que el texto se guarde.
import java.io.*;
public class WriteDemo {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(10);
writer.println(20);
writer.close(); // save the file
System.out.println("wrote data.txt");
}
}
Reading numbers with Scanner
new Scanner(new File("data.txt"))opens the file for reading.in.hasNextInt()istruewhile there is another whole number to read.in.nextInt()reads the next whole number. Callin.close()when done.
Leer números con Scanner
new Scanner(new File("data.txt"))abre el archivo para lectura.in.hasNextInt()estruemientras haya otro número entero para leer.in.nextInt()lee el siguiente número entero. Llama ain.close()cuando termines.
import java.io.*;
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) { // more numbers?
total = total + in.nextInt();
}
in.close();
System.out.println(total);
}
}
Reading whole lines
- Sometimes a line is text, not a number. Then read lines instead.
in.hasNextLine()istruewhile there is another line.in.nextLine()reads the whole next line as aString.
Leer líneas enteras
- A veces una línea es texto, no un número. Entonces lee líneas en su lugar.
in.hasNextLine()estruemientras exista otra línea.in.nextLine()lee la próxima línea completa comoString.
hasNext()(noIntorLine) checks for the next word, andnext()reads one word.- The pattern is always: check with a
hasNext...method, then read with the matching method.
import java.io.*;
import java.util.Scanner;
public class ReadLines {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("data.txt"));
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("read: " + line);
}
in.close();
}
}
hasNext()(sinIntniLine) busca la siguiente palabra, ynext()lee una palabra.- El patrón es siempre: comprobar con un método
hasNext..., luego leer con el método correspondiente.
Write then read in one program
- In each task your program first writes a file, then reads the same file back.
- This means you can run it again and again and get the same result.
Escribir y luego leer en un solo programa
- En cada tarea, tu programa primero escribe un archivo y luego lee ese mismo archivo nuevamente.
- Esto significa que puedes ejecutarlo una y otra vez y obtener el mismo resultado.
import java.io.*;
import java.util.Scanner;
public class RoundTrip {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter("data.txt");
writer.println(3);
writer.println(4);
writer.close();
Scanner in = new Scanner(new File("data.txt"));
int total = 0;
while (in.hasNextInt()) {
total = total + in.nextInt();
}
in.close();
System.out.println(total); // 7
}
}
Common mistakes
nextInt()leaves the newline, so a followingnextLine()reads an empty line.- Check
hasNext()before reading to avoid running off the end.
Errores comunes
nextInt()deja el salto de línea, por lo que unnextLine()posterior lee una línea vacía.- Verifica
hasNext()antes de leer para evitar excederte al final.
Now you try
- Each task pre-fills a class. Write the file first, then read it back, as the prompt asks.
- Remember the
throws IOExceptiononmain, andclose()both the writer and theScanner. - Press Run to compile and run, then Check answer.
Ahora tú intentas
- Cada tarea prellena una clase. Escribe el archivo primero, luego léelo nuevamente, según lo solicite el enunciado.
- Recuerda el
throws IOExceptionenmain, yclose()tanto del escritor como delScanner. - Presiona Run para compilar y ejecutar, luego Check answer.
First write the numbers 10, 20, 5, 7 to · hasta data.txt (one per line) with a PrintWriter. Then open it with new Scanner(new File("data.txt")) and use hasNextInt/nextInt to add them up. Print only the total. Expected output: 42. · Primero escribe los números 10, 20, 5, 7 a data.txt (uno por línea) con un PrintWriter. Luego ábrelo con new Scanner(new File("data.txt")) y usa hasNextInt/nextInt para sumarlos. Imprime solo el total. Salida esperada: 42.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
First write the lines apple, banana, cherry to · hasta words.txt with a PrintWriter. Then open it with a Scanner and use hasNextLine/nextLine to count the lines. Print only the count. Expected output: 3. · Primero escribe las líneas apple, banana, cherry a words.txt con un PrintWriter. Luego ábrelo con un Scanner y usa hasNextLine/nextLine para contar las líneas. Imprime solo el conteo. Salida esperada: 3.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.