1 Programmazione Programmazione ad ad Oggetti Oggetti JAVA

annuncio pubblicitario
JAVA Input/Output
Programmazione ad Oggetti
• Basato sul concetto di stream
• Stream: sequenza ordinata di dati che hanno
una sorgente (input stream) o una destinazione
(output stream)
• Astrazione dai dettagli del sistema operativo
sottostante
• Stessa interfaccia verso sorgenti dei dati diverse
quali un file su disco, una connessione di rete o
una stringa di caratteri
Java Input-Ouput classes
Marco Botta
Dipartimento di Informatica - Universita` degli Studi d i Torino
C.so Svizzera, 185 - I-10149 Torino (Italy)
e-mail: botta@d i.unito .it - URL: http://www.di.unito.it/~botta
Slide design: Matteo Baldoni
e-mail: baldoni @di.unito.it - URL: http://www.di.unito.it/~baldoni
Ingegneria del Software: Programmazione ad Oggetti
JAVA Input/Output
InputStream
public abstract int read() throws IOException
public int read(byte[] buf) throws IOException
public int read(byte[] buf, int off, int len) throws
IOException
public long skip(long count) throws IOException
public int available() throws IOException
• Le classi sono definite nel package java.io che
deve essere importato esplicitamente
• Java distingue tra stream per input, per output e
per input/output
• Gerarchia di classi InputStream
• Gerarchia di classi OutputStream
• In Java la classe File descrive le caratteristiche di
un file (nome, lunghezza, permessi di accesso,
etc.) e non le operazioni di lettura/scrittura
Ingegneria del Software: Programmazione ad Oggetti
2
public void close() throws IOException
3
OutputStream
class CountSpace {
public static void main(String args[]) throws IOException {
InputStream in = (args.length == 0)
? System.in
: new FileInputStream(args [0]);
int ch, total, spaces = 0;
for (total=0; ((ch = in.read()) != -1); total++)
if (Character.isSpace((char) ch)) spaces++;
System.out.println(total+ ” chars, “+spaces+” spaces”);
}
}
Ingegneria del Software: Programmazione ad Oggetti
4
JAVA Input/Output
public abstract void write(int b) throws IOException
public void write(byte[] buf ) throws IOException
public void write(byte[] buf , int off, int len) throws
IOException
public void flush() throws IOException
public void close() throws IOException
class Translate {
public static void main(String args []) throws IOException {
InputStream in = System.in;
OutputStream out = System.out;
String from = args[0], to = args[1];
int ch, i;
while ((c h = in.read()) != -1) {
if ((i = from.indexOf(c h)) != -1) out.write(to.charAt(i));
else out.write( ch);
}
public static void error(String err) { ... }
Ingegneria del Software: Programmazione ad Oggetti
}
5
• Non esiste un metodo open definito per
InputStream e OutputStream
• Un file è aperto automaticamente dal costruttore
FileInputStream o FileOutputStream
• InputStream e OutputStream sono classi astratte
e non possono essere istanziate
Ingegneria del Software: Programmazione ad Oggetti
6
1
JAVA Input/Output
JAVA Input/Output
import java.io.*;
class WordCount {
public static int words=0;
public static int lines=0;
public static int chars=0;
public static void wc(InputStream f) throws IOException {
int c=0;
boolean lastNotWhite=false;
String whiteSpace = " \t\n\r";
while ((c = f.read()) != -1) {
chars++;
if (c == '\n') { lines++; }
if (whiteSpace.indexOf(c) != -1) {
if (lastNotWhite) { words++; }
lastNotWhite = false;
} else { lastNotWhite = true; }
}
}
Ingegneria del Software: Programmazione ad Oggetti
public static void main(String args[]) {
FileInputStream f;
try {
if (args.length == 0) { // We're working with stdin
f = new FileInputStream(System.in);
wc(f);
} else { // We're working with a list of files
for (int i=0; i < args.length; i++) {
f = new FileInputStream(args [i]);
wc(f);
}
}
} catch (IOException e) { return; }
System.out.println(lines + " " + words + " " + chars);
}
}
7
• In Java non esiste una funzione analoga alla scanf
del C per l’input formattato
• Java definisce una classe di oggetti chiamata
StreamTokenizer che trasforma una InputStream
in una sequenza di token (parole)
• Il metodo nextToken() parsifica il prossimo token
in input e ne restituisce il tipo
public static void wc (InputStream f) throws IOException
{
int c=0;
PushbackInputStream pbf = new PushbackInputStream(f);
String whiteSpace = " \t\n\r";
while ((c = pbf.read()) != -1) {
chars++;
if (c == '\n') { lines++; }
if (whiteSpace.indexOf(c) != -1) {
c = pbf.read();
if ( whiteSpace. indexOf(c) != -1) { words++; }
pbf.unread(c);
}
}
}
• TT_WORD : una parola
• TT_NUMBER : un numero
• TT_EOL : fine linea
• TT_EOF : fine stream
9
JAVA Input/Output
StreamTokenizer
public static void wc(InputStream f) throws IOException {
StreamTokenizer tok = new StreamTokenizer(f);
tok.resetSyntax();
tok.wordChars (33, 255);
tok.whitespaceChars (0, ' ');
tok.eolIsSignificant(true);
int tokenType = tok.nextToken();
while (tok.ttype != StreamTokenizer.TT_EOF) {
switch (tokenType) {
case StreamTokenizer.TT_EOL:
lines++;
chars++;
break;
case StreamTokenizer.TT_WORD:
words++;
default: // FALLSTHROUGH
chars += tok.sval.length();
break;
}
tokenType = tok.nextToken();
}
Ingegneria del Software: Programmazione ad Oggetti
}
8
JAVA Input/Output
StreamTokenizer
JAVA Input/Output
Ingegneria del Software: Programmazione ad Oggetti
Ingegneria del Software: Programmazione ad Oggetti
Ingegneria del Software: Programmazione ad Oggetti
10
PrintStream
• Realizza l’output dei valori in formato caratteri
stampabili
• aggiunge metodi print e println per ogni tipo
di dato standard
• print e println richiamano un metodo toString
per convertire il parametro in input in formato
caratteri stampabili
• per stampare un oggetto definito dall’utente
basta ridefinire il metodo toString
11
Ingegneria del Software: Programmazione ad Oggetti
12
2
PrintStream
class Entry {
String name;
String address;
String phone;
...
public String toString () {
return(name+ ” “+address+” “+phone);
}
}
class test {
public static void main(String args[]) {
PrintStream out = System.out;
Entry[] addressBook = new Entry[10];
...
int i;
for (i=0; i< addressBook .length; i++)
out.println(addressBook[i]);
}
}
Ingegneria del Software: Programmazione ad Oggetti
13
3
Scarica