java.io - streams and files

Post on 11-Feb-2017

489 views 0 download

Transcript of java.io - streams and files

marcello.thiry@gmail.comPackage java.io: streams and files

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

Supplementary material

marcello.thiry@gmail.com 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.

Basic Glossary

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

A numerical value assigned to each

character in a character set

repertoire

Can be represented by one or more bytes

Code Point Code Position

marcello.thiry@gmail.com

Code Point Code Position

A = 41hex (ASCII)

a = 61hex (ASCII)

A = 00hex 41hex (UNICODE)

= 33hex 34hex (UNICODE)

a = 00hex 61hex (UNICODE)

= 42hex F4hex (UNICODE)

A coded character set*

*Sometimes called code page

UNICODE

marcello.thiry@gmail.com

The way algorithm the coded

characters are stored into memory

Character Encoding

UTF-8

UTF-16

UTF-32

marcello.thiry@gmail.com

Character Encoding

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

marcello.thiry@gmail.com

Sequence of data elements made

available over time

Stream

marcello.thiry@gmail.com

Which data elements?

Byte raw binary data

Character

Primitive data type

Object

Stream

marcello.thiry@gmail.com

A continuous stream of bytes

stored in a file system

Stream File

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

marcello.thiry@gmail.com

Region of a physical memory

storage used to temporarily store

data while it is being moved from

one place to another

Data Buffer

marcello.thiry@gmail.com

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

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

Streams in Java

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

Optimizes input and output by

reducing the number of calls to

the native API

And a buffered stream?

marcello.thiry@gmail.com

Where to use?

Files

Network connections sockets

Blob database fields

System.in standard input

System.out standard output

To write/read into/from

marcello.thiry@gmail.com

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

/api/java/io/InputStream.html

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

/api/java/io/OutputStream.html

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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()...

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

Source

of data

marcello.thiry@gmail.com

Input stream for

reading BYTES from

a FILE

Binary files

UNICODE files

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

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

From this point forward, all

our examples will use the

Try-with-resources statement

marcello.thiry@gmail.com

Destination

of data sink

marcello.thiry@gmail.com

Output stream

for writing

BYTES to a FILE

Binary files

UNICODE files

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

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

And if I want to

write or read

objects from a stream?

marcello.thiry@gmail.com

marcello.thiry@gmail.com

marcello.thiry@gmail.com

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

Explore yourself!

marcello.thiry@gmail.com

And beyond!

Using text files

In Java

marcello.thiry@gmail.com

Source

of data

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

class FileReader

Reads character files

Default character encoding

Default byte-buffer size

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

marcello.thiry@gmail.com

String fileName = "temp.txt";

String line;

FileReader fileReader = new FileReader(fileName);

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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);

}

}

marcello.thiry@gmail.com

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);

}

}

marcello.thiry@gmail.com

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);

}

}

marcello.thiry@gmail.com

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);

}

}

marcello.thiry@gmail.com

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) {...

}

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

class InputStreamReader

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

For top efficiency, consider

wrapping within a BufferedReader

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

Now we can use

FileInputStream e

InputStreamReader to

read a UNICODE file

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

Destination

of data

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

String fileName = “temp.txt";

FileWriter fileWriter = new FileWriter(fileName);

FileWriter fileWriter = new FileWriter(fileName, false);

FileWriter fileWriter = new FileWriter(fileName, true);

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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

marcello.thiry@gmail.com

class OutputStreamWriter

For top efficiency, consider

wrapping within a BufferedWriter

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

marcello.thiry@gmail.com

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) {}

marcello.thiry@gmail.com

Now we can use

FileOutputStream e

OutputStreamWriter to

write into a UNICODE file

marcello.thiry@gmail.com

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) {...}

marcello.thiry@gmail.com

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/.