Entrée et Sortie http://java.sun.com/docs/books/tutorial/essential/io/

publicité
Entrée et Sortie
http://java.sun.com/docs/books/tutorial/essential/io/
Entrée/Sortie
 La plupart de la communication avec l’utilisateur ce
fait à travers la ligne de commande (Command line)
ou des fichiers
 La ligne de commande est accédé avec la commande
CMD dans l’option Exécuter dans le menu de
Démarrer
Lire de la ligne de commande
import java.io.Console;
import java.io.IOException;
public class Nom {
public static void main (String args[]) throws IOException {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String prenom = c.readLine("Tapez votre prénom: ");
String surnom = c.readLine("Tapez votre surnom: ");
System.out.println ("Ton nom est " + prenom + " " + surnom);
}
}
Lire d’un fichier
(un caractère à la fois)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class copieCaracteres {
public static void main(String[] args) throws IOException {
FileReader streamEntree = null;
FileWriter streamSortie = null;
try {
streamEntree = new FileReader("xanadu.txt");
streamSortie = new FileWriter("characteroutput.txt");
int c;
while ((c = streamEntree.read()) != -1) {
streamSortie(c);
}
} finally {
if (streamEntree != null) {
streamEntree();
}
if (streamSortie != null) {
streamSortie.close();
}
}
}
}
Lire d’un fichier
(une ligne à la fois)
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class copieLignes {
public static void main(String[] args) throws IOException {
BufferedReader streamEntree = null;
PrintWriter streamSortie = null;
try {
streamEntree = new BufferedReader(new FileReader("xanadu.txt"));
streamSortie = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = streamEntree.readLine()) != null) {
streamSortie.println(l);
}
} finally {
if (streamEntree != null) {
streamEntree.close();
}
if (streamSortie != null) {
streamSortie.close();
}
}
}
}
Téléchargement