java.io - streams and files
TRANSCRIPT
[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
[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.
Basic Glossary
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
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
A numerical value assigned to each
character in a character set
repertoire
Can be represented by one or more bytes
Code Point Code Position
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
The way algorithm the coded
characters are stored into memory
Character Encoding
UTF-8
UTF-16
UTF-32
Character Encoding
http://www.w3.org/International/articles/definitions-characters/
Which data elements?
Byte raw binary data
Character
Primitive data type
Object
Stream
A continuous stream of bytes
stored in a file system
Stream File
http://ebiznet2u.com/wp-content/uploads/2012/07/file-viewer.jpg
Region of a physical memory
storage used to temporarily store
data while it is being moved from
one place to another
Data Buffer
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
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
Optimizes input and output by
reducing the number of calls to
the native API
And a buffered stream?
Where to use?
Files
Network connections sockets
Blob database fields
System.in standard input
System.out standard output
…
To write/read into/from
https://docs.oracle.com/javase/8/docs
/api/java/io/InputStream.html
https://docs.oracle.com/javase/8/docs
/api/java/io/OutputStream.html
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
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()...
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
Input stream for
reading BYTES from
a FILE
Binary files
UNICODE files
https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html
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) {...}
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) {...}
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
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) {...}
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) {...}
From this point forward, all
our examples will use the
Try-with-resources statement
Output stream
for writing
BYTES to a FILE
Binary files
UNICODE files
https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html
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) {...}
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) {...}
Explore yourself!
And beyond!
Using text files
In Java
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
class FileReader
Reads character files
Default character encoding
Default byte-buffer size
https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html
String fileName = "temp.txt";
String line;
FileReader fileReader = new FileReader(fileName);
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
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);
}
}
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);
}
}
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);
}
}
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);
}
}
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) {...
}
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
class InputStreamReader
https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html
For top efficiency, consider
wrapping within a BufferedReader
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) {...}
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) {...}
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
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
String fileName = “temp.txt";
FileWriter fileWriter = new FileWriter(fileName);
FileWriter fileWriter = new FileWriter(fileName, false);
FileWriter fileWriter = new FileWriter(fileName, true);
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) {...}
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
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) {...}
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
class OutputStreamWriter
For top efficiency, consider
wrapping within a BufferedWriter
https://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html
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) {}
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) {...}
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/.