Java I/O: Jussi Pohjolainen Tampere University of Applied Sciences
Java I/O: Jussi Pohjolainen Tampere University of Applied Sciences
I/O
Jussi
Pohjolainen
Tampere
University
of
Applied
Sciences
Intro
Input
/
Output
Input
from
le
or
keyboard
Output
to
screen
or
a
le
Input
Stream:
System.in
PrintStream (System.out)
InputStream (System.in)
Using
InputStreamReader
To
use
InputStreamReader
InputStreamReader a = new InputStreamReader(System.in);
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specied charset InputStreamReader has methods for reading one char at a Kme We dont want to read one char at a .me from user!
Using
BueredReader
To
use
InputStreamReader
BufferedReader a = new BufferedReader(new InputStreamReader(System.in)); String mj = a.readLine();
Read text from a character-input stream, buering characters so as to provide for the ecient reading of characters, arrays, and lines. Done!
Scanner
Or
just
use
Scanner
from
Java
1.5!
Scanner s = new Scanner(System.in); String mj = s.nextLine();
Binary
vs
text
All
data
are
in
the
end
binary:
01010101001011100110
Binary les: bits represent encoded informaKons, executable instrucKons or numeric data. Text les: the binarys represent characters.
Text
les
In
text
les
bits
represent
printable
characters
In
ASCII
encoding,
one
byte
represents
one
character
Encoding
is
a
rule
where
you
map
chars
to
integers.
a => 97 => 1100001
TesKng
in
Java
class CharTest { public static void main(String [] args) { char myChar1 = 'a'; int myChar2 = 97; System.out.println(myChar1); // 'a' System.out.println(myChar2); // 97 System.out.println( (int) myChar1); // 97 System.out.println((char) myChar2); // 'a' } }
Character
Streams
Java
uses
UTF-8
internally
To
read
characters
FileReader
To
write
characters
FileWriter
FileReader
import java.io.FileReader; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { FileReader inputStream = new FileReader("CharTest.java"); char oneChar = (char) inputStream.read(); System.out.println(oneChar); inputStream.close(); } }
FileWriter
import java.io.FileWriter; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { FileWriter outputStream = new FileWriter("output.txt"); outputStream.write("hello!"); outputStream.close(); } }
Buering
Using
unbuered
IO
is
less
ecient
than
using
buered
IO.
Read
stu
to
buer
in
memory
and
when
buer
is
full,
write
it.
Less
disk
access
or
network
acKvity
BueredReader
import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class CharTest { public static void main(String[] args) throws IOException { BufferedReader inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); inputStream.close(); } }
PrintWriter,
BueredWriter
Convenient
way
of
wriKng
les
using
PrintWriter:
PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter("output.txt"))); pw.println("hello!"); pw.close();
To
Write
FileOutputStream
CLOSING STREAMS
import java.io.*; public class CharTest { public static void main(String[] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader("output.txt")); System.out.println( inputStream.readLine() ); } catch(IOException e) { e.printStackTrace(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch(IOException e) { e.printStackTrace(); } } } }
File
File
class
has
very
useful
methods:
exists
canRead
canWrite
Length
getPath
Example
File f = new File(file.txt); If(f.exists()) { .. }
SERIALIZATION
Object
Streams
To
read
and
write
objects!
How?
Object
class
must
implement
serializable
marker
interface
Read
and
write
using
ObjectInputStream
and
ObjectOutputStream
Example:
Car
class Car implements Serializable { private String brand; public Car(String brand) { setBrand(brand); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } }
Transient
Every
a^ribute
of
the
object
is
saved
into
disk..
except
a^ribute
is
marked
with
transient
keyword
Mark
a^ributes
to
transient
when
the
informaKon
is
secret
or
uneccessary.
When
object
is
deserializaled,
transient
a^ributes
values
are
null
JAVA NIO
Streams
vs
Blocks
java.io
Stream:
movement
of
single
bytes
one
at
a
Kme.
java.nio
Block:
movement
of
many
bytes
(blocks)
at
a
Kme
Processing
data
by
block
can
be
much
faster
than
one
byte
at
a
Kme
Buer
Types
There
are
many
classes
for
buers.
These
classes
inherit
java.nio.Buer:
ByteBuer
-
byte
array
CharBuer
ShortBuer
IntBuer
LongBuer
FloatBuer
DoubleBuer
About
Channels
You
never
write
a
byte
directly
into
a
channel.
Bytes
must
be
wrapped
inside
a
buer
Channels
are
bi-direcTonal
Channels
can
be
opened
for
reading,
wriKng,
or
both
Example:
Reading
FileInputStream
n
=
new
FileInputStream(
"data.txt"
);
//
Get
a
channel
via
the
FileInputStream
FileChannel
fc
=
n.getChannel();
//
Create
a
buer
ByteBuer
buer
=
ByteBuer.allocate(
1024
);
//
Read
from
channel
into
a
buer
fc.read(
buer
);
Example:
WriKng
FileOutputStream fout = new FileOutputStream( "data.txt" ); // Get a channel via the FileOutputStream FileChannel fc = fout.getChannel(); // Create a buffer ByteBuffer buffer = ByteBuffer.allocate( 1024 ); // Data to be saved byte [] message = "this will be saved".toByteArray(); // Write into buffer for ( int i=0; i<message.length; i++ ) { buffer.put( message[i] ); } // Flip the buffer, this will be explained later buffer.flip(); // Writes SOME bytes from the buffer! fc.write( buffer );
Buer
Internals
Every
buer
has
posiKon,
limit
and
capacity
These
three
variables
track
the
state
of
the
buer
posiTon:
is
the
index
of
the
next
element
to
be
read
or
wri^en.
A
buer's
posiKon
is
never
negaKve
and
is
never
greater
than
its
limit.
limit:
is
the
index
of
the
rst
element
that
should
not
be
read
or
wri^en.
A
buer's
limit
is
never
negaKve
and
is
never
greater
than
its
capacity
capacity:
is
the
number
of
elements
buer
contains.
The
capacity
of
a
buer
is
never
negaKve
and
never
changes.
Buer Example 1
Buer Example 2
Buer Example 3
Buer Example 4
Buer Example 5
Buer Example 6
Buer Example 7
FileInputStream fin = new FileInputStream( infile.exe ); FileOutputStream fout = new FileOutputStream( outfile.exe ); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 ); while (true) { // Reset the buffer buffer.clear(); int numberOfReadBytes = fcin.read( buffer ); if ( numberOfReadBytes == -1 ) { break; } // prepare the buffer to be written to a buffer buffer.flip(); int numberOfWrittenBytes = 0; do { numberOfWrittenBytes += fcout.write( buffer ); } while(numberOfWrittenBytes < numberOfReadBytes); }