java.io - streams and files

71
[email protected] Package java.io: streams and files http://3.bp.blogspot.com/- Eg1r_jQcFFk/UcAVENEyKYI/AAAA AAAAADc/5fgJlvZUlp4/s1600/sr22 -file-and-filing-cabinet.jpg Supplementary material

Upload: marcello-thiry

Post on 11-Feb-2017

492 views

Category:

Education


0 download

TRANSCRIPT

Page 1: java.io - streams and files

[email protected] java.io: streams and files

http://3.bp.blogspot.com/-Eg1r_jQcFFk/UcAVENEyKYI/AAAAAAAAADc/5fgJlvZUlp4/s1600/sr22-file-and-filing-cabinet.jpg

Supplementary material

Page 2: java.io - streams and files

[email protected] http://ideas.scup.com/pt/files/2013/06/conte%C3%BAdo.jpg

1. Basic glossary

2. Streams and files in Java (reading and writing)

3. Text files in Java (reading and writing)

Contents.

Page 3: java.io - streams and files

Basic Glossary

Page 4: java.io - streams and files

[email protected]

if you do not know much about

charsets, code pages, encoding,

ASCII, UNICODE, etc.

Before we start…

Take a look in this article

http://www.joelonsoftware.com/articles/Unicode.html

The Absolute Minimum Every Software Developer Absolutely,

Positively Must Know About Unicode and Character Sets (No Excuses!)by Joel Spolsky

It’s a bit old, but a good start

Page 5: java.io - streams and files

[email protected]

Set of characters you can use

Charset Repertoire

ISO-8859-1 - Western Alphabet ISO-8859-5 - Cyrillic Alphabet

JIS X 0208 - Japanese Alphabet ISO-8859-7 - Greek Alphabet

Page 6: java.io - streams and files

[email protected]

A numerical value assigned to each

character in a character set

repertoire

Can be represented by one or more bytes

Code Point Code Position

Page 7: java.io - streams and files

[email protected]

Code Point Code Position

A = 41hex (ASCII)

a = 61hex (ASCII)

A = 00hex 41hex (UNICODE)

= 33hex 34hex (UNICODE)

a = 00hex 61hex (UNICODE)

= 42hex F4hex (UNICODE)

Page 8: java.io - streams and files

A coded character set*

*Sometimes called code page

UNICODE

Page 9: java.io - streams and files

[email protected]

The way algorithm the coded

characters are stored into memory

Character Encoding

UTF-8

UTF-16

UTF-32

Page 10: java.io - streams and files

[email protected]

Character Encoding

http://www.w3.org/International/articles/definitions-characters/

Page 11: java.io - streams and files

[email protected]

Sequence of data elements made

available over time

Stream

Page 12: java.io - streams and files

[email protected]

Which data elements?

Byte raw binary data

Character

Primitive data type

Object

Stream

Page 13: java.io - streams and files

[email protected]

A continuous stream of bytes

stored in a file system

Stream File

http://ebiznet2u.com/wp-content/uploads/2012/07/file-viewer.jpg

Page 14: java.io - streams and files

[email protected]

Region of a physical memory

storage used to temporarily store

data while it is being moved from

one place to another

Data Buffer

Page 15: java.io - streams and files

[email protected]

Conversion of an object to a series

of bytes, which lets a program

write whole objects out to streams

and read them back again

Object Serialization

Page 16: java.io - streams and files

Set of routines, protocols, and

tools to access a software

component/module without the need

to know details of its

implementation

Application Programming*

Interface API

*Also used: program

Page 17: java.io - streams and files

Streams in Java

Page 18: java.io - streams and files

[email protected]

Bytes

Characters automatically translates to and

from the local character set

Data primitive data type and String values

Objects

What is a stream in Java?

handle I/O of

Page 19: java.io - streams and files

[email protected]

Optimizes input and output by

reducing the number of calls to

the native API

And a buffered stream?

Page 20: java.io - streams and files

[email protected]

Where to use?

Files

Network connections sockets

Blob database fields

System.in standard input

System.out standard output

To write/read into/from

Page 21: java.io - streams and files

[email protected]

https://docs.oracle.com/javase/8/docs

/api/java/io/InputStream.html

https://docs.oracle.com/javase/8/docs

/api/java/io/OutputStream.html

Page 22: java.io - streams and files

[email protected]

read() reads a single byte

read(byte[] b) reads b.length bytes into an array

read(byte[] b, int off, int len) reads len bytes into an array,

starting from the position off

skip(long n) skips discards n bytes

close() closes the stream

https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html

Page 23: java.io - streams and files

[email protected]

mark(int readlimit) marks the current position in

this input stream

reset() repositions this stream to the position at

the time the mark method was last called

https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html

And, if markSupported()...

Page 24: java.io - streams and files

[email protected]

write(int b) writes a single byte

write(byte[] b) writes b.length bytes from the array

write(byte[] b, int off, int len) writes len bytes from the array

starting at offset off

flush() forces any buffered output bytes to be written

out

Page 25: java.io - streams and files

[email protected]

Source

of data

Page 26: java.io - streams and files

[email protected]

Input stream for

reading BYTES from

a FILE

Binary files

UNICODE files

https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html

Page 27: java.io - streams and files

[email protected]

String fileName = "c:/temp/file.exe";

int byteValue;

try {

InputStream in = new FileInputStream(fileName);

while ((byteValue = in.read()) != -1) {

System.out.format("[%2X]\n", byteValue);

}

in.close();

}

catch (IOException ex) {...}

Page 28: java.io - streams and files

[email protected]

String fileName = "c:/temp/file.exe";

int byteValue;

try {

InputStream in = new FileInputStream(fileName);

while ((byteValue = in.read()) != -1) {

System.out.format("[%2X]\n", byteValue);

}

in.close();

}

catch (IOException ex) {...}

Page 29: java.io - streams and files

[email protected]

FileNotFoundException

For constructors that use a file

name as an argument

If the named file does not exist, is a

directory rather than a regular file, or

for some other reason cannot be opened

for reading

Page 30: java.io - streams and files

[email protected]

Try-with-resources

String fileName = "c:/temp/file.exe";

byte[] bytes = new byte[500];

int read;

try {

try (InputStream in = new FileInputStream(fileName)) {

while ((read = in.read(bytes)) != -1) {

System.out.format("%d bytes read:\n", read);

for (int i = 0; i < read; i++) {

System.out.format("[%2X]", bytes[i]);

}

System.out.println();

}

}

} catch (IOException ex) {...}

Page 31: java.io - streams and files

[email protected]

Try-with-resources

String fileName = "c:/temp/file.exe";

byte[] bytes = new byte[500];

int read;

try {

try (InputStream in = new FileInputStream(fileName)) {

while ((read = in.read(bytes)) != -1) {

System.out.format("%d bytes read:\n", read);

for (int i = 0; i < read; i++) {

System.out.format("[%2X]", bytes[i]);

}

System.out.println();

}

}

} catch (IOException ex) {...}

Page 32: java.io - streams and files

[email protected]

From this point forward, all

our examples will use the

Try-with-resources statement

Page 33: java.io - streams and files

[email protected]

Destination

of data sink

Page 34: java.io - streams and files

[email protected]

Output stream

for writing

BYTES to a FILE

Binary files

UNICODE files

https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html

Page 35: java.io - streams and files

[email protected]

String fileName = "d:/downloads/mynewfile.txt";

try {

try (OutputStream out = new FileOutputStream(fileName)) {

byte[] bytes = new byte[]{'T', 'E', 'S', 'T', 32, 0x41};

out.write(bytes);

}

} catch (IOException e) {...}

Page 36: java.io - streams and files

[email protected]

And if I want to

write or read

objects from a stream?

Page 40: java.io - streams and files

[email protected]

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.dat"))) {

out.writeObject(new User("a", "a"));

out.writeObject(new User("b", "b"));

out.writeObject(new User("c", "c"));

out.flush();

} catch (IOException e) {...}

User u;

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.dat"))) {

for (int i = 0; i < 3; i++) {

u = (User) in.readObject();

System.out.println(u.getLogin() + ", " + u.getPassword());

}

} catch (IOException | ClassNotFoundException e) {...}

Page 41: java.io - streams and files

[email protected]

Explore yourself!

Page 42: java.io - streams and files

[email protected]

And beyond!

Page 43: java.io - streams and files

Using text files

In Java

Page 44: java.io - streams and files

[email protected]

Source

of data

Page 45: java.io - streams and files

[email protected]

class Reader

Abstract class for reading

character streams

read(): reads a single character

read(char[]): reads characters into an array

skip(long): skips N characters

close(): closes the stream

https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html

Page 46: java.io - streams and files

[email protected]

class FileReader

Reads character files

Default character encoding

Default byte-buffer size

https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html

Page 47: java.io - streams and files

[email protected]

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

Page 48: java.io - streams and files

[email protected]

class BufferedReader

Usually wraps FileReader to

improve efficiency

https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

Buffer size may be specified

Reading of characters, arrays, and lines

Page 49: java.io - streams and files

[email protected]

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

}

Page 50: java.io - streams and files

[email protected]

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

}

Page 51: java.io - streams and files

[email protected]

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

}

Page 52: java.io - streams and files

[email protected]

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

}

Page 53: java.io - streams and files

[email protected]

String fileName = “temp.txt";

String line;

try {

FileReader fileReader = new FileReader(fileName);

try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

}

} catch (FileNotFoundException ex) {...

} catch (IOException ex) {...

}

Page 54: java.io - streams and files

[email protected]

But what about the class

InputStreamReader?

https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html

Reads bytes and decodes them into

characters using a specified charset

Bridge from byte streams to

character streams

Page 55: java.io - streams and files

[email protected]

class InputStreamReader

https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html

For top efficiency, consider

wrapping within a BufferedReader

Page 56: java.io - streams and files

[email protected]

String line;

try {

InputStreamReader inputReader = new InputStreamReader(System.in);

try (BufferedReader bufferedReader = new BufferedReader(inputReader)) {

while (!"".equals(line = bufferedReader.readLine())) {

System.out.println(line);

}

}

} catch (IOException e) {...}

Page 57: java.io - streams and files

[email protected]

Now we can use

FileInputStream e

InputStreamReader to

read a UNICODE file

Page 58: java.io - streams and files

[email protected]

try {

FileInputStream in = new FileInputStream("c:/temp/fileUTF16.txt");

InputStreamReader inReader = new InputStreamReader(in, "UTF-16");

try (BufferedReader buffReader = new BufferedReader(inReader)) {

int character;

while ((character = buffReader.read()) != -1) {

System.out.print((char) character);

}

}

} catch (IOException e) {...}

Page 59: java.io - streams and files

[email protected]

Destination

of data

Page 60: java.io - streams and files

[email protected]

class Writer

Abstract class for writing to

character streams

write(int): writes a single character

write(char[]): writes an array of characters

write(String): writes a string

close(): closes the stream

https://docs.oracle.com/javase/8/docs/api/java/io/Writer.html

Page 61: java.io - streams and files

[email protected]

class FileWriter

Writes in character files

Default character encoding

Default byte-buffer size

https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html

Page 62: java.io - streams and files

[email protected]

String fileName = “temp.txt";

FileWriter fileWriter = new FileWriter(fileName);

FileWriter fileWriter = new FileWriter(fileName, false);

FileWriter fileWriter = new FileWriter(fileName, true);

Page 63: java.io - streams and files

[email protected]

String fileName = "c:/temp.txt";

try {

try (FileWriter fileWriter = new FileWriter(fileName)) {

fileWriter.write("My first line");

fileWriter.write("\r\n"); // new line - windows

fileWriter.write("My second line");

}

} catch (IOException e) {...}

Page 64: java.io - streams and files

[email protected]

class BufferedWriter

Usually wraps FileWriter to

improve efficiency

https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html

Buffer size may be specified

Writing characters, arrays, and lines

Page 65: java.io - streams and files

[email protected]

String fileName = "c:/temp/MyFile.txt";

try {

FileWriter writer = new FileWriter(fileName, true);

try (BufferedWriter buffWriter = new BufferedWriter(writer)) {

buffWriter.write("My first line");

buffWriter.newLine();

buffWriter.write("My second line!");

}

} catch (IOException e) {...}

Page 66: java.io - streams and files

[email protected]

But what about the class

OutputStreamWriter?

https://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html

Characters written to it are encoded

into bytes using a specified charset

bridge from character to byte

streams

Page 67: java.io - streams and files

[email protected]

class OutputStreamWriter

For top efficiency, consider

wrapping within a BufferedWriter

https://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html

Page 68: java.io - streams and files

[email protected]

try {

OutputStreamWriter outWriter = new OutputStreamWriter(System.out);

try (BufferedWriter buffWriter = new BufferedWriter(outWriter)) {

buffWriter.write("Printing a line on the console");

buffWriter.newLine();

buffWriter.write("Printing a second line...\r\n");

}

} catch (IOException e) {}

Page 69: java.io - streams and files

[email protected]

Now we can use

FileOutputStream e

OutputStreamWriter to

write into a UNICODE file

Page 70: java.io - streams and files

[email protected]

String fileName = "c:/temp/MyNewFile.txt";

try {

FileOutputStream out = new FileOutputStream(fileName);

OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-16");

try (BufferedWriter buffWriter = new BufferedWriter(outWriter)) {

buffWriter.write("UNICODE text");

buffWriter.newLine();

buffWriter.write("Some more...");

}

} catch (IOException e) {...}

Page 71: java.io - streams and files

[email protected]

References.

Java™ Platform, Standard Edition 8 API Specification.

https://docs.oracle.com/javase/8/docs/api/overview-summary.html.

The Java™ Tutorials. https://docs.oracle.com/javase/tutorial/.