Input/Output in Java - Marco Ronchetti

Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
1
Input/Output in Java
Vedi anche:
http://java.sun.com/docs/books/tutorial/essential/io/index.html
2
Formattazione
public class Root2 {
public static void main(String[] args) {
int i = 2;
double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n",
i, r);
}
}
System.out.format("%f, %<+020.10f %n", Math.PI);
3.141593, +00000003.1415926536
1
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
3
Formattazione
d formats an integer value as a decimal value;
f formats a floating point value as a decimal value;
n outputs a locale-specific line terminator.
x formats an integer as a hexadecimal value;
s formats any value as a string;
tB formats an integer as a locale-specific month name.
4
Streams
To bring in information, a program opens a stream on an
information source (a file, memory, a socket) and reads the
information serially, like this:
2
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Streams
5
Similarly, a program can send
information to an external destination by
opening a stream to a destination and
writing the information out serially, like
this:
Streams
6
No matter where the information is coming
from or going to and no matter what type of
data is being read or written, the algorithms
for reading and writing data is pretty much
always the same.
Reading
Writing
open a stream
while more information
read information
close the stream
open a stream
while more information
write information
close the stream
3
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Streams
7
The java.io package contains a collection of
stream classes that support these algorithms for
reading and writing. These classes are divided into
two class hierarchies based on the data type (either
characters or bytes) on which they operate.
8
Raw IO from stdin,stdout
import java.io.*;
public class Simple {
public static void main(String a[]){
new Simple();
}
public Simple() {
String s=null;
byte buffer[]=new byte[100];
String s=null;
System.out.println("Dammi una stringa");
try {
int letti=System.in.read(buffer);
s=new String(buffer,0,letti);
} catch (IOException e) { e.printSTackTrace(); }
System.out.println(s.length()+":“
+s.indexOf('\n')+":"+s);
}
}
4
Programmazione 2 – 2002/2003
Università degli Studi di Trento
9
Marco Ronchetti
Lezione 1
Simple IO from stdin,stdout
import java.io.*;
public class Simple {
public static void main(String a[]){
new Simple();
}
public Simple() {
String s=null; is=new BufferedReader(
BufferedReader
BufferedReader
new InputStreamReader(System.in));
is=new BufferedReader(
System.out.println("Dammi
new InputStreamReader(System.in));
una stringa");
try {
System.out.println("Dammi
una stringa");
trys=is.readLine();
{
} catch
s=is.readLine();
(IOException e) { e.printStackTrace();}
System.out.println(s.length()+":“
}
catch (IOException e) { e.printStackTrace();}
+s.indexOf('\n')+":"+s);
System.out.println(s.length()+":“
}
+s.indexOf('\n')+":"+s);
}}
}
10
Reading an int from stdin
import java.io.*;
public class Simple {
public static void main(String a[]){
new Simple();
}
public Simple() {
String s=null;
BufferedReader is=new BufferedReader(new
InputStreamReader(System.in));
int i=0;
System.out.println("Dammi un int");
try { s=is.readLine();
} catch (IOException e) { e.printStackTrace();}
try{ i=Integer.parseInt(s);
System.out.println("Hai scritto "+i);
} catch (NumberFormatException e) {
System.out.println("Input non valido");
}
}
}
5
Programmazione 2 – 2002/2003
Università degli Studi di Trento
11
Marco Ronchetti
Lezione 1
package IO;
import java.awt.*;
import java.io.*;
public class Application1 {
public static void main(String[] args) {
new Application1();
}
public Application1() {
Frame fr=new Frame();
FileDialog fd=new FileDialog(fr);
fd.show();
String filename=fd.getFile();
String pathname=fd.getDirectory();
System.out.println(pathname+" "+filename);
File file=new File(pathname,filename);
try {
FileWriter fw=new FileWriter(file);
fw.write("Hello World");
fw.close();
} catch (IOException e) {}
}
}
12
However, it's often more convenient to group the classes based
on their purpose rather than on the data type they read and write.
Thus, we can cross-group the streams by whether they read from
and write to data "sinks" or process the information as its being
read or written.
6
Programmazione 2 – 2002/2003
Università degli Studi di Trento
13
Marco Ronchetti
Lezione 1
Character Streams
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).
14
Character Streams
7
Programmazione 2 – 2002/2003
Università degli Studi di Trento
15
Marco Ronchetti
Lezione 1
Byte Streams
Programs should use the byte
streams, descendants of
InputStream and OutputStream,
to read and write
8-bit bytes. InputStream and
OutputStream provide the API
and some implementation for input
streams (streams that read 8-bit
bytes) and output streams (streams
that write 8-bit bytes). These
streams are typically used to read
and write binary data such as
images and sounds.
As with Reader and Writer,
subclasses of InputStream and
OutputStream provide specialized
I/O that falls into two categories:
data sink streams and processing
streams.
16
IO superclasses - reading
Understanding the I/O Superclasses
Reader and InputStream define similar APIs but for different data types.
For example, Reader contains these methods for reading characters and
arrays of characters:
int read()
int read(char cbuf[])
int read(char cbuf[], int offset, int length)
InputStream defines the same methods but for reading bytes and arrays of
bytes:
int read()
int read(byte cbuf[])
int read(byte cbuf[], int offset, int length)
Also, both Reader and InputStream provide methods for marking a location
in the stream, skipping input, and resetting the current position.
8
Programmazione 2 – 2002/2003
Università degli Studi di Trento
17
Marco Ronchetti
Lezione 1
IO superclasses - writing
Understanding the I/O Superclasses
Writer and OutputStream are similarly parallel. Writer defines these
methods for writing characters and arrays of characters:
int write(int c)
int write(char cbuf[ ])
int write(char cbuf[ ], int offset, int length)
And OutputStream defines the same methods but for bytes:
int write(int c)
int write(byte cbuf[ ])
int write(byte cbuf[ ], int offset, int length)
All of the streams--readers, writers, input streams, and output streams--are
automatically opened when created. You can close any stream explicitly by
calling its close method. Or the garbage collector can implicitly close it,
which occurs when the object is no longer referenced.
18
Standard IO
The Standard I/O Streams
The concept of standard input and output streams is a C library concept that has
been assimilated into the Java environment. There are three standard streams, all
of which are managed by the java.lang.System class:
Standard input--referenced by System.in (instance of InputStream)
Used for program input, typically reads input entered by the user.
Standard output--referenced by System.out (instance of PrintStream)
Used for program output, typically displays information to the user.
Standard error--referenced by System.err (instance of PrintStream)
Used to display error messages to the user.
9
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Data sink streams
19
Sink Type Character
Streams
Byte Streams
Memory
CharArrayReader,
CharArrayWriter
ByteArrayInputStream,
ByteArrayOutputStream
StringReader,
StringWriter
StringBufferInputStream
Pipe
PipedReader,
PipedWriter
PipedInputStream,
PipedOutputStream
File
FileReader,
FileWriter
FileInputStream,
FileOutputStream
Processing streams
20
Sink Type
Character
Streams
Byte Streams
Buffering
BufferedReader,
BufferedWriter
BufferedInputStream,
BufferedOutputStream
Filtering
FilterReader,
FilterWriter
FilterInputStream,
FilterOutputStream
Converting
Bytes/Chars
InputStreamReader,
OutputStreamWriter
Concatenation
SequenceInputStream
10
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Processing streams
21
Sink Type
Character
Streams
Byte Streams
Object
Serialization
ObjectInputStream,
ObjectOutputStream
Data
Conversion
DataInputStream,
DataOutputStream
Counting
LineNumberReader
Peeking Ahead PushbackReader
Printing
PrintWriter
LineNumberInputStream
PushbackInputStream
PrintStream
Classi accessorie
22
File
Represents a file on the native file system. You can create a File object for a
file on the native file system and then query the object for information about
that file (such as its full pathname).
FileDescriptor
Represents a file handle (or descriptor) to an open file or an open socket.
You will not typically use this class.
StreamTokenizer
Breaks the contents of a stream into tokens. Tokens are the smallest unit
recognized by a text-parsing algorithm (such as words, symbols, and so on).
A StreamTokenizer object can be used to parse any text file. For example,
you could use it to parse a Java source file into variable names, operators,
and so on, or to parse an HTML file into HTML tags.
FilenameFilter
Used by the list method in the File class to determine which files in a
directory to list. The FilenameFilter accepts or rejects files based on their
names. You could use FilenameFilter to implement simple regular
expression style file search patterns such as foo*.
11
Programmazione 2 – 2002/2003
Università degli Studi di Trento
23
Marco Ronchetti
Lezione 1
Classi accessorie
CheckedInputStream and CheckedOutputStream
An input and output stream pair that maintains a checksum as the data is being
read or written.
DeflaterOutputStreamand InflaterInputStream
Compresses or uncompresses the data as it is being read or written.
GZIPInputStream and GZIPOutputStream
Reads and writes compressed data in the GZIP format.
ZipInputStream and ZipOutputStream
Reads and writes compressed data in the ZIP format.
24
Esempio 1
Input/Output
12
Programmazione 2 – 2002/2003
Università degli Studi di Trento
25
Marco Ronchetti
Lezione 1
Esempio: copy - 1
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File(“originale.txt");
File outputFile = new File(“copia.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1) out.write(c);
in.close();
out.close();
}
py
Co
}
26
Esempio: copy - 2
Remember that FileReader and FileWriter read and write
16-bit characters. However, most native file systems are
based on 8-bit bytes. These streams encode the characters
as they operate according to the default character-encoding
scheme.
You can find out the default character-encoding by using
System.getProperty("file.encoding").
To specify an encoding other than the default, you should
construct an OutputStreamWriter on a
FileOutputStream and specify it.
13
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Esempio: copy - 3
27
public class CopyBytes {
public static void main(String[] args) throws IOException{
File inputFile = new File(“originale.txt");
File outputFile = new File(“copia.txt");
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new
FileOutputStream(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
s
in.close()
yte
B
out.close();
py
Co
}
}
Java
Serialization
14
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Il problema della persistenza
Persistenza dei dati
quando l’applicazione non è running:
salvataggio della struttura interna di un oggetto.
E’ un problema ricorsivo!
Serializzazione: trasformazione di oggetti in
“stream di dati” (seriali).
Il JDK prevede delle API per la serializzazione,
e la maggior parte delle sue classi sono serializzabili.
persistenza selettiva
Le variabili dichiarate
transient
non vengono serializzate.
15
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Supporto di JDK alla persistenza
ObjectOutputStream: converte oggetti dalla
rappresentazione
in memoria a quella serializzata.
ObjectInputStream: converte oggetti dalla
rappresentazione
serializzata a quella in memoria.
Serializable: interfaccia senza metodi che marca una classe
come seralizzabile.
Externalizable: interfaccia con metodi (sottoclasse di
Serializable) che fornisce maggior controllo sul processo di
serializzazione.
ObjectInputValidation: interfaccia per verificare la corretta
decodifica di un oggetto.
Principali Metodi di ObjectOutputstream
ObjectOutputStream(OutputStream) costruttore
writeObject(Object) serializza Object
close()
flush()
reset()
writeInt(int)
writeFloat(float)
writeDouble(double)
16
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Principali Metodi di ObjectInputstream
ObjectInputStream(InputStream) costruttore
Object readObject() deserializza Object
available()
dice quanti bytes ci sono da leggere
int readInt()
float writeFloat()
double writeDouble()
Esempio –Writer 1/2
package serialDemo;
import java.io.*;
import java.util.*;
public class Writer {
HashMap hm=new HashMap();
public Writer() {
System.out.println("WRITER-------------------------");
for (int k=1;k<=10;k+=2) {
String key=new String("a"+k);
Integer ik=new Integer(k);
hm.put(key,ik);
}
System.out.println(hm.size());
Iterator i=hm.keySet().iterator();
while (i.hasNext()) {
Object o=i.next();
System.out.println(o.toString()+"#"+
hm.get(o).toString());
}
17
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Esempio –Writer 2/2
FileOutputStream ofs=null;
ObjectOutputStream oos=null;
try {
ofs=new FileOutputStream("serializedStream.txt");
oos=new ObjectOutputStream(ofs);
oos.writeObject(hm);
}
catch (IOException ex) { ex.printStackTrace();
}
}
//--------------------------------------------public static void main(String[] args) {
Writer writer = new Writer();
}
}
Esempio –Reader 1/2
package serialDemo;
import java.io.*;
import java.util.*;
public class Reader {
HashMap hm=null;
//-----------------------------------------public static void main(String[] args) {
Reader reader = new Reader();
}
18
Programmazione 2 – 2002/2003
Università degli Studi di Trento
Marco Ronchetti
Lezione 1
Esempio –Reader 2/2
public Reader() {
System.out.println("READER -------------------------");
FileInputStream ofs=null;
ObjectInputStream oos=null;
try {
ofs=new FileInputStream("serialiazidStream.txt");
oos=new ObjectInputStream(ofs);
hm=(HashMap)oos.readObject();
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}catch (IOException ex) { ex.printStackTrace();
}
System.out.println(hm.size());
Iterator i=hm.keySet().iterator();
while (i.hasNext()) {
Object o=i.next();
System.out.println(o.toString()+" #“
+hm.get(o).toString());
}
}
19