0% found this document useful (0 votes)
4 views40 pages

Chapitre1 Streams

Chapter 1 discusses Java I/O Streams, highlighting how they facilitate data transfer in networking applications with minimal code. It explains the concepts of input and output streams, their classes, and methods for reading and writing both byte and character data. Additionally, it covers the use of standard I/O streams, data streams, and object serialization in Java.

Uploaded by

okba.harkat.04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views40 pages

Chapitre1 Streams

Chapter 1 discusses Java I/O Streams, highlighting how they facilitate data transfer in networking applications with minimal code. It explains the concepts of input and output streams, their classes, and methods for reading and writing both byte and character data. Additionally, it covers the use of standard I/O streams, data streams, and object serialization in Java.

Uploaded by

okba.harkat.04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

CHAPTER 1

JAVA I/O STREAMS


CHAPTER 1 : JAVA I/O STREAMS

Introduction
• A striking observation that can be made when looking at
functional networking applications is how little code is
dedicated to the networking aspects themselves.

• The part of a program dedicated to networking aspects is


almost always the shortest and simplest.

• For Java applications, for example, it is easy to send and


receive data over the Internet.

• Much of what a network program does is input and output:


moving bytes from one system to another.
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• To a large extent, reading data sent by a server is no different
at all from reading from a file.
• Sending a text to a client isn't much different from writing to
a file.
• I/O in Java is based on the notion of Streams.
• A stream is an ordered sequence of bytes.
• We can think of a stream as a data structure that allows
reading or writing sequentially without the possibility of
backtracking.
Un Stream d’Entrée est une source de données

Un Stream de Sortie est une destination des données


CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• Input streams read data; output streams write data.

• Different stream classes, like java.io.FileInputStream and


sun.net.TelnetOutputStream read and write particular data
sources.

• However, all output streams have the same basic methods


for writing data and all input streams have the same basic
methods for reading data.
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams


• The class java.io.InputStream is the base class for all Java IO input streams :
• public abstract class IntputStream
• This class provides the fundamental methods needed to read raw bytes.
These are:
 public abstract int read() throws IOException
 public int read(byte[] input) throws IOException
 public int read(byte[] input, int offset, int length) throws IOException
 public long skip(long n) throws IOException
 public int available() throws IOException
 public void close() throws IOException
• InputStream subclasses use these methods to read data from particular
media.
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams


• The class java.io.OutputStream is the base class for all Java IO output streams :
• public abstract class OutputStream
• This class provides the fundamental methods needed to write raw bytes.
These are:
 public abstract void write(int b) throws IOException
 public void write(byte[] data) throws IOException
 public void write(byte[] data, int offset, int length) throws IOException
 public void flush() throws IOException
 public void close() throws IOException

• OutputStream subclasses use these methods to write data from particular


media.
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams


• Streams are synchronous; i.e., when a program (actually a
thread) asks a stream to read or write a piece of data, it
waits for the data to be read or written before doing
anything else.

• Java also offers non-blocking I/O using pipes and buffers.

• Non-blocking I/O is a bit more complicated, but can be much


faster in some high-volume applications, like web servers.
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams


• Streams are abstractions that allow access to external
resources without much concern for the specific resource.

• Using the Streams Library is a two-step process:

 Creating the stream object


 Reading/Writing data (through the stream object).
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams Classes


• The java.io package contains a relatively large number of
classes that support input and output operations. These
classes may be categorized into groups based on the data
type on which they operate.

• Byte Stream Classes that provide support for handling I/O


operations on bytes.
• Character Stream Classes that provide support for managing
I/O operations on characters.
CHAPTER 1 : JAVA I/O STREAMS

Java I/O Streams Classes


CHAPTER 1 : JAVA I/O STREAMS

Byte Stream Classes


• To read and write 8-bit bytes, programs should use the byte streams,
descendents of InputStream and OutputStream.
• These streams are typically used to read and write binary data such as
images and sounds.
• Two of the byte stream classes, ObjectInputStream and
ObjectOutputStream, are used for object serialization.
• Subclasses of InputStream and OutputStream provide specialized I/O
that falls into two categories, as shown in the following class hierarchy
figure: data sink streams (shaded) and processing streams (unshaded)
CHAPTER 1 : JAVA I/O STREAMS

Byte Stream Classes Hierarchy


CHAPTER 1 : JAVA I/O STREAMS

Character Stream Classes


• Reader and Writer are the abstract superclasses for character streams in
java.io.
• Reader provides the API and partial implementation for readers — streams
that read 16-bit characters — and
• Writer provides the API and partial implementation for writers — streams
that write 16-bit characters.
• Subclasses of Reader and Writer implement specialized streams and are
divided into two categories:
those that read from or write to data sinks (shown in gray in the following
figures) and
those that perform some sort of processing (shown in white). The following
figure shows the class hierarchies for the Reader and Writer classes.
CHAPTER 1 : JAVA I/O STREAMS

Character Stream Classes Hierarchy


CHAPTER 1 : JAVA I/O STREAMS

Byte Streams
Example - Reading and Writing Bytes :
// Reading from an InputStream
InputStream inStream = new FileInputStream("input.txt");
int byteData;
while ((byteData = inStream.read()) != -1) {
// Process byteData
}
CHAPTER 1 : JAVA I/O STREAMS

Byte Streams
// Writing to an OutputStream
OutputStream outStream = new FileOutputStream("output.txt");
byte[] dataToWrite = "Hello, World!".getBytes();
outStream.write(dataToWrite);
outStream.close();
CHAPTER 1 : JAVA I/O STREAMS

Character Streams
Example - Reading and Writing Characters :
// Reading from a Reader
Reader lire = new FileReader("input.txt");
int charData;
while ((charData = lire.read()) != -1) {
// Process charData
}
CHAPTER 1 : JAVA I/O STREAMS

Byte Streams

// Writing to a Writer
Writer ecrire = new FileWriter("output.txt");
String textToWrite = "Hello, World!";
ecrire.write(textToWrite);
ecrire.close();
CHAPTER 1 : JAVA I/O STREAMS

Java Standard I/O Streams


CHAPTER 1 : JAVA I/O STREAMS

Java Standard I/O Streams


• System.in:This is the standard input stream that is used to read
characters from the keyboard or any other standard input device.
• System.out: This is the standard output stream that is used to
produce the result of a program on an output device like the
computer screen.
• System.err:This is the standard error stream that is used to output all
the error data that a program might throw, on a computer screen or
any standard output device.
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• Les readers et writers peuvent être chainés aux input et output
streams pour permettre aux programmes de lire ou écrire du texte
(c.à.d. cacarctères) plutôt que des bytes.

• Proprement utilisés, les readers et writers peuvent prendre en charge


une variété de codage de caractères, incluant des ensembles de
caractères mulibyte tells que UTF-8 ou SJIS.
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• Les Filter streams peuvent être chainés soit à un input stream soit à
un output stream.

• Les Filters peuvent modifier les données lorsqu’elles sont lues ou


écrites, par exemple, en les cryptant ou compressant, ou bien ils
peuvent simplement fournir des méthodes additionnelles pour
convertir les données en d’autre formats.

• Par exemple, la classe java.io.DataOutputStream fournit une méthode


qui convertis un int en quatre bytes et écrit ces bytes dans l’output
stream sous-jacent.
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams public class CopyBytes {


• public static void main(String[] args) throws IOException {
import java.io.FileInputStream; • FileInputStream in = null;
import java.io.FileOutputStream;
• FileOutputStream out = null;
import java.io.IOException;
• try {
• in = new FileInputStream("xanadu.txt");
• out = new FileOutputStream("outagain.txt");
• int c;

• while ((c = in.read()) != -1) {


• out.write(c);
• }
• } finally {
• if (in != null) {
• in.close();
• }
• if (out != null) { out.close();} } }}
CHAPTER 1 : JAVA I/O STREAMS

Character Streams
• La plate-forme Java stocke les valeurs des caractères en utilisant les conventions
Unicode. L'entrée/sortie de character streams traduit automatiquement ce
format interne depuis et vers le jeu de caractères local.

• Toutes les classes de character streams descendent du Reader et du Writer.


• Comme pour les byte streams, il existe des classes de charecter streams
spécialisées dans les E/S de fichiers : FileReader et FileWriter.

• Les streams de caractères sont souvent des "enveloppes" pour les byte streams.
Le stream de caractères utilise le byte stream pour effectuer les E/S physiques,
tandis que le stream de caractères gère la traduction entre les caractères et les
bytes.

• Il existe deux flux "pont" d'octet à caractère d'usage général :


InputStreamReader et OutputStreamWriter.
CHAPTER 1 : JAVA I/O STREAMS

Streams public class CopyCharacters {


import java.io.FileReader; public static void main(String[] args) throws IOException {
import java.io.FileWriter;
import java.io.IOException; FileReader inStream = null;
FileWriter outStream = null;

try {
inStream = new FileReader("xanadu.txt");
outStream = new FileWriter("characteroutput.txt");

int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inpStream.close();
}
if (outStream != null) {
outStream.close();
} } }}
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• Les entrées/sorties de caractères se font généralement par unités plus
grandes que les caractères individuels. Une unité commune est la
ligne : une chaîne de caractères avec un terminateur de ligne à la fin.

• Un terminateur de ligne peut être une séquence retour chariot/saut


de ligne ("\r\n"), un simple retour chariot ("\r") ou un simple saut de
ligne ("\n").

• La prise en charge de tous les terminateurs de ligne possibles permet


aux programmes de lire des fichiers texte créés sur n'importe quel
système d'exploitation largement utilisé.
CHAPTER 1 : JAVA I/O STREAMS

Streams public class CopyLines {


public static void main(String[] args) throws IOException {
import java.io.FileReader;
import java.io.FileWriter; BufferedReader intStream = null;
import java.io.BufferedReader; PrintWriter outStream = null;
import java.io.PrintWriter;
import java.io.IOException; try {
inStream = new BufferedReader(new FileReader("xanadu.txt"));
ouStream = new PrintWriter(new
FileWriter("characteroutput.txt"));

String l;
while ((l = inStream.readLine()) != null) {
outStream.println(l);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.close(); } } }}
CHAPTER 1 : JAVA I/O STREAMS

Streams
• La plupart des exemples que nous avons vus jusqu'à présent utilisent des E/S
non tamponnées. Cela signifie que chaque demande de lecture ou d'écriture est
traitée directement par le système d'exploitation sous-jacent.
• Cela peut rendre un programme beaucoup moins efficace, car chacune de ces
demandes déclenche souvent un accès au disque, une activité réseau ou une
autre opération relativement coûteuse.

• Pour réduire ce type de surcharge, la plate-forme Java met en œuvre des flux
d'E/S tamponnés. Les flux d'entrée tamponnés lisent les données d'une zone de
mémoire appelée tampon.

• l'API d'entrée native n'est appelée que lorsque le tampon est vide. De même,
les flux de sortie tamponnés écrivent des données dans un tampon, et l'API de
sortie native n'est appelée que lorsque le tampon est plein.
CHAPTER 1 : JAVA I/O STREAMS

Streams
• Les data streams prennent en charge l'E/S binaire des valeurs de type
de données primitives (booléen, char, octet, court, int, long, flottant
et double) ainsi que les valeurs de type String.

• Tous les streams de données implémentent soit l'interface DataInput,


soit l'interface DataOutput.

• Les implémentations les plus utilisées de ces interfaces,


DataInputStream et DataOutputStream.
Data Streams
Order Data type Data description Output Method Input Method Value
1 double Item price DataOutputStream.writeDouble DataInputStream.readDouble 19.99
2 int Unit count DataOutputStream.writeInt DataInputStream.readInt 12
"Java T-
3 String Item description DataOutputStream.writeUTF DataInputStream.readUTF
Shirt"

static final String dataFile = "invoicedata";

static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };


static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = {
"Java T-shirt",
"Java Mug",
"Duke Juggling Dolls",
"Java Pin",
"Java Key Chain"
};
Data Streams
Order Data type Data description Output Method Input Method Value
1 double Item price DataOutputStream.writeDouble DataInputStream.readDouble 19.99
2 int Unit count DataOutputStream.writeInt DataInputStream.readInt 12
"Java T-
3 String Item description DataOutputStream.writeUTF DataInputStream.readUTF
Shirt"

out = new DataOutputStream(new BufferedOutputStream(


new FileOutputStream(dataFile)));

// DataStreams writes out the records and closes the output stream.

for (int i = 0; i < prices.length; i ++) {


out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
Data Streams
in = new DataInputStream(new
BufferedInputStream(new FileInputStream(dataFile)));

double price;
int unit;
String desc;
double total = 0.0;

// Maintenant, les DataStreams peuvent lire chaque enregistrement du stream, en faisant un rapport sur les données qu'ils
rencontrent.

try {
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d" + " units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch (EOFException e) { }
CHAPTER 1 : JAVA I/O STREAMS

I/O Streams
• Tout comme les streams de données supportent les E/S de types de données
primitifs, les streams d'objets supportent les E/S d'objets.

• La plupart des classes standard, mais pas toutes, prennent en charge la sérialisation
de leurs objets. Celles qui le font implémentent l'interface de marquage Serializable.

• Les classes de stream d'objets sont ObjectInputStream et ObjectOutputStream.

• Ces classes implémentent ObjectInput et ObjectOutput, qui sont des sous-interfaces


de DataInput et DataOutput.

• Cela signifie que toutes les méthodes d'E/S de données primitives couvertes dans
Data Streams sont également implémentées dans les flux d'objets.

• Un stream d'objets peut donc contenir un mélange de valeurs primitives et d'objets.


Object Streams
import java.io.*;
import java.math.BigDecimal;
import java.util.Calendar;

public class ObjectStreams {


static final String dataFile = "invoicedata";

static final BigDecimal[] prices = {


new BigDecimal("19.99"),
new BigDecimal("9.99"),
new BigDecimal("15.99"),
new BigDecimal("3.99"),
new BigDecimal("4.99") };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = { "Java T-shirt",
"Java Mug",
"Duke Juggling Dolls",
"Java Pin",
"Java Key Chain" };
Object Streams Calendar date = null;
public static void main(String[] args) BigDecimal price;
throws IOException, ClassNotFoundException { int unit;
String desc;
BigDecimal total = new BigDecimal(0);
ObjectOutputStream out = null;
try { date = (Calendar) in.readObject();
out = new ObjectOutputStream(new
BufferedOutputStream(new System.out.format ("On %tA, %<tB %<te, %<tY:%n", date);
FileOutputStream(dataFile)));
try {
out.writeObject(Calendar.getInstance()); while (true) {
for (int i = 0; i < prices.length; i ++) { price = (BigDecimal) in.readObject();
out.writeObject(prices[i]); unit = in.readInt();
out.writeInt(units[i]); desc = in.readUTF();
out.writeUTF(descs[i]); System.out.format("You ordered %d units of %s at $%.2f%n",
} unit, desc, price);
} finally { total = total.add(price.multiply(new BigDecimal(unit)));
out.close(); }
} } catch (EOFException e) {}
System.out.format("For a TOTAL of: $%.2f%n", total);
ObjectInputStream in = null; } finally { in.close(); } } }
try {
in = new ObjectInputStream(new
BufferedInputStream(new
FileInputStream(dataFile)));
CHAPTER 1 : JAVA I/O STREAMS

Java User Input (Scanner)


• The Scanner class is used to get ExampleGet your own Java Server
user input, and it is found in the import java.util.Scanner; // Import the Scanner class
java.util package. class Main {
• To use the Scanner class, create public static void main(String[] args) {
an object of the class and use // Create a Scanner object
Scanner myObj = new Scanner(System.in);
any of the available methods System.out.println("Enter username");
found in the Scanner class // Read user input
documentation. String userName = myObj.nextLine();
// Output user input
• In our example, we will use the System.out.println("Username is: " + userName);
nextLine() method, which is
used to read Strings: }
}
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:
CHAPTER 1 : JAVA I/O STREAMS

Java User Input (Scanner)

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


CHAPTER 1 : JAVA I/O STREAMS

Java Output methods


The System.out stream, short for "output", is used together
with different methods to output values or print text to the
console:

Method Description

print() Prints text or values the console

printf() Prints formatted text or values to the console

println() Prints text or values to the console, followed by a new line


CHAPTER 1 : JAVA I/O STREAMS

Java Output methods


TProblem
You need to reassign one or more of the standard streams System.in, System.out, or
System.err.
Solution
Construct an InputStream or PrintStream as appropriate, and pass it to the appropriate
setmethod in the System class.
// Redirect.java
String LOGFILENAME = "error.log";
System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME)));
System.out.println("Please look for errors in " + LOGFILENAME);
// Now to see somebody else's code writing to stderr...
int a[] = new int[5];
a[10] = 0; // here comes an ArrayIndexOutOfBoundsException

The stream you use can be one that you’ve opened, as here, or one you inherited:

System.setErr(System.out); // merge stderr and stdout to same output file.

You might also like