Text files: write and read with Scanner · Fichiers texte : écrire et lire avec 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.
Lire et écrire des fichiers texte
- Un fichier texte stocke du texte qui persiste sur le disque après la fin du programme.
- Pour lire un fichier en Java, nous utilisons un
Scannerconnecté à unFile. - Pour écrire un fichier, nous utilisons un
PrintWriter. Dans cette leçon, chaque programme écrit un fichier, puis le relit. - Leçon bonus : l'examen AP CSA ne teste pas l'entrée/sortie de fichiers. Apprenez ceci pour les vrais programmes — vous ne serez pas évalué dessus.
Reading and writing a file · Lecture et écriture dans un fichier
A file is used in three steps: open · ouvrir it, read or write lines, then close · fermer it. · Un fichier est utilisé en trois étapes : ouvrir le fichier, lire ou écrire des lignes, puis fermer le fichier.
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.
Les imports nécessaires
- Les outils de fichiers se trouvent dans deux endroits, nous importons donc les deux en haut.
import java.io.*;— pourFile,PrintWriteretIOException.import java.util.Scanner;— pour le lecteurScanner.
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.
Les fichiers peuvent échouer, nous mettons throws IOException
- Lire ou écrire un fichier peut échouer (le fichier peut manquer).
- Java vous oblige à gérer cela. La méthode la plus simple est d'ajouter
throws IOExceptionàmain. - Cela signifie "si une erreur de fichier survient, laissez le programme s'arrêter". C'est acceptable pour ces tâches.
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.
Écrire un fichier avec PrintWriter
new PrintWriter("data.txt")crée (ou vide) un fichier nommédata.txt.- Utilisez
writer.println(...)pour écrire une ligne, comme imprimer à l'écran. - Appelez toujours
writer.close()à la fin, afin que le texte soit sauvegardé.
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.
Lire des nombres avec Scanner
new Scanner(new File("data.txt"))ouvre le fichier en lecture.in.hasNextInt()esttruealors qu'il y a un autre nombre entier à lire.in.nextInt()lit le prochain nombre entier. Appelezin.close()quand c'est fini.
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.
Lire des lignes complètes
- Parfois, une ligne contient du texte, pas un nombre. Lisez alors des lignes au lieu de ça.
in.hasNextLine()esttruetandis qu'il y a une autre ligne.in.nextLine()lit la prochaine ligne complète en tant queString.
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()(sansIntniLine) vérifie la présence du prochain mot, etnext()lit un mot.- Le motif est toujours : vérifier avec une méthode
hasNext..., puis lire avec la méthode correspondante.
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.
Écrire puis lire dans un seul programme
- Dans chaque exercice, votre programme écrit d'abord un fichier, puis relit ce même fichier.
- Vous pouvez ainsi le lancer encore et encore et obtenir le même résultat.
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.
Erreurs courantes
nextInt()laisse le saut de ligne, donc unnextLine()suivant lit une ligne vide.- Vérifiez
hasNext()avant de lire pour éviter de dépasser la fin.
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.
À vous maintenant
- Chaque exercice pré-remplit une classe. Écrivez d'abord le fichier, puis relisez-le, comme demandé par l'énoncé.
- N'oubliez pas
throws IOExceptionsurmain, etclose()à la fois l'auteur et leScanner. - Appuyez sur Exécuter pour compiler et exécuter, puis sur Vérifier la réponse.
First write the numbers 10, 20, 5, 7 to · à 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. · Écrivez d'abord les nombres 10, 20, 5, 7 vers data.txt (un par ligne) avec un PrintWriter. Ensuite, ouvrez-le avec new Scanner(new File("data.txt")) et utilisez hasNextInt/nextInt pour les additionner. N'imprimez que le total. Sortie attendue : 42.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
First write the lines apple, banana, cherry to · à 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. · Écrivez d'abord les lignes apple, banana, cherry vers words.txt avec un PrintWriter. Ensuite, ouvrez-le avec un Scanner et utilisez hasNextLine/nextLine pour compter les lignes. N'imprimez que le compteur. Sortie attendue : 3.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.