« Bonjour, Amigo ! Aujourd'hui, tu vas apprendre comment faire quelque chose de nouveau : remplacer l'objet System.out. »
System.out - est une variable PrintStream statique appelée out dans la classe System. Cette variable a le modificateur final, tu lui affectes donc simplement une nouvelle valeur. Cependant, la classe System a une méthode spéciale pour cela : setOut(PrintStream stream). Et c'est ce que nous allons utiliser.
« Intéressant. Et par quoi ça va la remplacer ? »
« Nous avons besoin d'un objet qui peut recueillir les données de sortie. ByteArrayOutputStream est la classe la mieux adaptée à cette tâche. C'est une classe spéciale qui est un tableau dynamique (redimensionnable) et implémente l'interface OutputStream. »
« Un adaptateur entre un tableau et OutputStream ? »
« Quelque chose comme ça, oui. Voici à quoi notre code ressemble. »
public static void main(String[] args) throws Exception
{
//Save the current PrintStream in a special variable
PrintStream consoleStream = System.out;
//Create a dynamic array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//Create an adapter for the PrintStream class
PrintStream stream = new PrintStream(outputStream);
//Set it as the current System.out
System.setOut(stream);
//Call a function that knows nothing about our changes
printSomething();
//Convert the data written to our ByteArray into a string
String result = outputStream.toString();
//Put everything back to the way it was
System.setOut(consoleStream);
}
public static void printSomething()
{
System.out.println("Hi");
System.out.println("My name is Amigo");
System.out.println("Bye-bye!");
}
« Et qu'est-ce qu'on fait avec cette ligne ? »
« Eh bien, tout ce que nous voulons. Par exemple, on pourrait l'inverser. Dans ce cas le code ressemblerait à ceci : »
public static void main(String[] args) throws Exception
{
//Save the current PrintStream in a special variable
PrintStream consoleStream = System.out;
//Create a dynamic array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//Create an adapter for the PrintStream class
PrintStream stream = new PrintStream(outputStream);
//Set it as the current System.out
System.setOut(stream);
//Call a function that knows nothing about our changes
printSomething();
//Convert the data written to our ByteArray into a string
String result = outputStream.toString();
//Put everything back to the way it was
System.setOut(consoleStream);
//Reverse the string
StringBuilder stringBuilder = new StringBuilder(result);
stringBuilder.reverse();
String reverseString = stringBuilder.toString();
//Output it to the console
System.out.println(reverseString);
}
public static void printSomething()
{
System.out.println("Hi");
System.out.println("My name is Amigo");
System.out.println("Bye-bye!");
}
« C'est super intéressant ! Maintenant, je commence à comprendre un peu les grandes possibilités que ces petites classes ouvrent. »
« Merci pour cette leçon intéressante, Bilaabo. »
GO TO FULL VERSION