J08-Java IO
J08-Java IO
Input/Output
http://softeng.polito.it/courses/09CBI
Version 4.1.0 - May 2019
© Marco Torchiano, 2019
Licensing Note
Under the following conditions:
▪ Attribution. You must attribute the work in the manner specified by
the author or licensor.
▪ Non-commercial. You may not use this work for commercial purposes.
▪ No Derivative Works. You may not alter, transform, or build upon this
work.
▪ For any reuse or distribution, you must make clear to others the
license terms of this work.
▪ Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
1
29-May-20
Stream
▪ All I/O operations rely on the abstraction of
stream (flow of elements)
▪ A stream can be linked to:
A file on the disk
Standard input, output, error
A network connection
A data-flow from/to whichever hardware device
▪ I/O operations work in the same way with
all kinds of stream
Stream
▪ Package: java.io
▪ Stream of chars (Unicode - 16 bit)
Reader / Writer
− All characters
▪ Stream of bytes (8 bit)
InputStream / OutputStream
− Binary data, sounds, images
▪ All related exceptions are subclasses
of IOException
2
29-May-20
Application
byte char
Encoding / Decoding
Data
Application
[c316,a816] ['è']
'è'
Encoding / Decoding
Unicode charset
c3a816
3
29-May-20
Readers
BufferedReader LineNum berReader
CharArrayReader
Reader
PipedReader
StringReader
Reader (abstract)
void close()
− Close the stream.
int read()
− Read a single character:
− Returns -1 when end of stream
int read(char[] cbuf)
− Read characters into an array.
int read(char[] cbuf,
int off, int len) Blocking methods
i.e. stop until
− Read characters into a portion • data available,
of an array. • I/O error, or
• end of stream
8
4
29-May-20
Reader (abstract)
▪ boolean ready()
− Tell whether the stream is ready to be read.
▪ void reset()
− Reset the stream, restart from beginning
▪ long skip(long n)
− Skip n characters
9
9
Read a char
int ch = r.read();
char unicode = (char) ch;
System.out.print(unicode);
r.close();
Character ch unicode
‘A’ 0…00000000 01000001bin = 65dec 65
‘\n’ 0…00000000 00001101bin = 13dec 13
End of file 1…11111111 11111111bin = -1dec -
10
5
29-May-20
Read a line
public static String readLine(Reader r)
throws IOException{
StringBuffer res= new StringBuffer();
int ch = r.read();
if(ch == -1) return null; // END OF FILE!
while( ch != -1 ){
char unicode = (char) ch;
if(unicode == '\n') break;
if(unicode != '\r’) res.append(unicode);
ch = r.read();
}
return res.toString();
}
11
Writers
Writers
pk g
2015/05/12 powered
BufferedWriter
CharArrayWriter
FilterWriter
PipedWriter
PrintWriter
StringWriter
12
6
29-May-20
Writer (abstract)
void write(int c)
Write a single character.
void write(char[] cbuf)
Write an array of characters.
void write(char[] cbuf, int off, int len)
Write a portion of an array of characters.
void write(String str)
Write a string.
close()
Close the stream, flushing it first.
abstract void flush()
Flush the stream.
13
13
Input streams
InputStreams 2015/05/12 powered by A
pk g
ByteArrayInputStream
FileInputStream DataInputStream
InputStream
ObjectInputStream PushBack InputStream
PipedInputStream
SequenceInputStream
14
7
29-May-20
InputStream
void close()
Closes this input stream and releases any
system resources associated with the stream.
int read()
Reads the next byte of data from the input
stream.
int read(byte[] b)
Reads some bytes from the input stream and
stores them into the buffer array b.
int read(byte[] b, int off, int len)
Reads up to len bytes of data from the input
stream into an array of bytes.
15
15
InputStream
int available()
Number of bytes that can be read (or skipped
over) from this input stream without blocking.
void reset()
Repositions this stream to the position at the
time the mark method was last called.
long skip(long n)
Skips over and discards n bytes of data from
this input stream.
16
16
8
29-May-20
Output streams
pk g
ByteArrayOutputStream
FileOutputStream BufferedOutputStream
ObjectOutputStream PrintStream
PipedOutputStream
17
OutputStream
void write(byte[] b)
Writes b.length bytes from the specified byte array to this
output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at
offset off to this output stream.
void write(int b)
Writes the specified byte to this output stream.
void close()
Closes this output stream and releases any system
resources associated with this stream.
void flush()
Flushes this output stream and forces any buffered output
bytes to be written out.
18
18
9
29-May-20
Stream specializations
▪ Memory
▪ Pipe
▪ File
▪ Buffered
▪ Printed
▪ Interpreted
19
19
20
20
10
29-May-20
Read/Write in memory
▪ CharArrayReader
▪ CharArrayWriter
▪ StringReader
▪ StringWriter
R/W chars from/to array or String
▪ ByteArrayInputStream
▪ ByteArrayOutputStream
R/W bytes from/to array in memory
21
21
R/W of Pipe
▪ Pipes are used for inter-thread
communication they must be used in
connected pairs
▪ PipedReader
▪ PipedWriter
R/W chars from pipe
▪ PipedInputStream
▪ PipedOutputStream
R/W bytes from pipe
22
22
11
29-May-20
R/W of File
▪ Used for reading/writing files
▪ FileReader
▪ FileWriter
R/W chars from file
▪ FileInputStream
▪ FileOutputStream
R/W bytes from file
23
23
24
24
12
29-May-20
25
25
Buffered
▪ BufferedInputStream
BufferedInputStream(InputStream i)
BufferedInputStream(InputStream i, int s)
▪ BufferedOutputStream
▪ BufferedReader
readLine()
▪ BufferedWriter
26
26
13
29-May-20
Printed streams
▪ PrintStream(OutputStream o)
Provides general printing methods for all
primitive types, String, and Object
− print()
− println()
Designed to work with basic byte-
oriented console
Does not throw IOException, but it sets
a bit, to be checked with method
checkError()
27
27
class System {
//…
static InputStream in;
static PrintStream out;
static PrintStream err;
}
28
28
14
29-May-20
29
Interpreted streams
▪ Translate primitive types into / from
standard format
Typically on a file
▪ DataInputStream(InputStream i)
readByte(), readChar(), readDouble(),
readFloat(), readInt(), readLong(),
readShort(), ..
▪ DataOutputStream(OutputStream o)
like write()
30
30
15
29-May-20
31
URL
▪ Represents a URL
Constructorthrows a
MalformedURLException
▪ Provide getters for URL portions:
− Protocol, Host, Port
− Path, Query, Anchor (Ref)
▪ Method openStream() opens a
connection and returns the relative
InputStream
32
16
29-May-20
Download file
URL home = new URL("http://…");
URLConnection con = home.openConnection();
String ctype = con.getContentType();
if(ctype.equals("text/html")){
Reader r = new InputStreamReader(
con.getInputStream());
Writer w = new OutputStreamWriter(System.out);
char[] buffer = new char[4096];
while(true){
int n = r.read(buffer);
if(n==-1) break;
w.write(buffer,0,n);
}
r.close(); w.close();
}
33
Stream as resources
▪ Streams consume OS resources
Should be closed as soon as possible to
release resources
34
17
29-May-20
String l = br.readLine();
br.close()
return l
}
What happens in case of
exception in readLine ?
35
36
18
29-May-20
Finally close
String readFirstLine(String path)
throws IOException {
BufferedReader br=new BufferedReader(
new FileReader(path));
try {
return br.readLine();
} finally {
if(br!=null) br.close();
}
}
Executed in any case
before exiting the method
37
Try-with-resource
String readFirstLine(String path)
throws IOException {
try(
BufferedReader br=new BufferedReader(
new FileReader(path))){
return br.readLine();
}
}
Works since BuffereReader
implements Autocloseable
public interface AutoCloseable{
public void close();
}
38
19
29-May-20
SERIALIZATION
39
Serialization
▪ Read / write of an object imply:
read/write attributes (and optionally the
type) of the object
Correctly separating different elements
When reading, create an object and set all
attributes values
▪ These operations (serialization) are
automated by
ObjectInputStream
ObjectOutputStream
40
40
20
29-May-20
Using Serialization
▪ Methods to read/write objects are:
void writeObject(Object)
Object readObject()
▪ ONLY objects implementing interface
Serializable can be serialized
Thisinterface is empty
Just used to avoid serialization of
objects, without permission of the class
developer
41
41
Type recovery
▪ When reading, an object is created
▪ ... but which is its type?
▪ In practice, not always a precise
downcast is required:
Only if specific methods need to be
invoked
A downcast to a common ancestor can be
used to avoid identifying the exact class
42
42
21
29-May-20
43
44
44
22
29-May-20
Serialization implements
public class Student
Serializable {…}
List<Student> students=new LinkedList<>();
students.add( ... );
...
ObjectOutputStream serializer =
new ObjectOutputStream(
new FileOutputStream(”std.dat"));
serializer.writeObject(students);
serializer.close();
ObjectInputStream deserializer =
new ObjectInputStream(
new FileInputStream("std.dat"));
Object retrieved = deserializer.readObject();
deserializer.close();
List<Student> l = (List<Student>)retrieved;
45
FILE SYSTEM
46
46
23
29-May-20
File
▪ Abstract pathname
directory, file, file separator
absolute, relative
▪ convert abstract pathname <--> string
▪ Methods:
create() delete() exists() , mkdir()
getName() getAbsolutePath(), getPath(),
getParent(), isFile(), isDirectory()
isHidden(), length()
listFiles(), renameTo()
47
47
48
24
29-May-20
New IO (nio)
▪ Paths and Files
Abstract path manipulation
Static methods
49
Class Path
▪ Represents path in the file system
Components extraction:
− E.g. getFileName()
Navigation:
− E.g. getParent(), getRoot()
Relative paths
− relativize()
− isAbsolute()
− resolve()
50
25
29-May-20
Class Files
▪ Provides methods to operate on Paths
Copy content: copy()
Create: createFile()
Test properties: isWritable()
Navigate: list(), find()
Create stream: newInputStream()
Create channel: newByteChannel()
Read: lines()
Write: write()
51
Example
▪ Compute max line length
Path d = Paths.get("file.txt")
int maxLen = 0;
if(Files.exists(d)){
maxLen = Files.lines(d).
mapToInt(String::length).
max().getAsInt();
}
52
26
29-May-20
Tokenizers
▪ StringTokenizer
Works on
− String to be tokenized
− set of delimiters
− Default: " \t\n\r\f"
▪ Divides a String in tokens (sequence of
characters separated by delimiters),
returning the tokens one by one
hasMoreTokens(): checks for more tokens
nextToken(): returns next token
− Does not distinguish identifiers, numbers,
comments, quoted strings
53
53
Tokenizers
▪ StreamTokenizer
Works on a stream (Reader)
More sophisticated, recognizes
identifiers, comments, quoted string,
numbers
use symbol table and flag
nextToken(), returns the type
− TT_EOF if at the end of file
Attribute sval contains the token
54
54
27
29-May-20
Summary
▪ Java IO is based on the stream
abstraction
▪ Two main stream families:
Char oriented: Reader/Writer
Byte oriented: Input/OutputStream
55
Summary
▪ Streams resources need to be closed
as soon as possible
Try-with-resource construct guarantee
resource closure even in case of
exception
▪ Serialization means saving/restoring
objects using Object streams
Serializable interface enables it
56
28