SlideShare una empresa de Scribd logo
1 de 60
Descargar para leer sin conexión
Java	
  I/O	
  
Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
Intro	
  
•  Input	
  /	
  Output	
  
–  Input	
  from	
  file	
  or	
  keyboard	
  
–  Output	
  to	
  screen	
  or	
  a	
  file	
  

•  To	
  deliver	
  data,	
  stream	
  is	
  used	
  
READ	
  AND	
  WRITE	
  CONSOLE	
  
Read	
  and	
  Write	
  to	
  Console	
  
•  Output	
  stream:	
  
–  System.out	
  

•  Input	
  Stream:	
  
–  System.in	
  
PrintStream	
  (System.out)	
  
InputStream	
  (System.in)	
  

Read	
  a	
  byte	
  from	
  user	
  input?	
  
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	
  specified	
  
charset	
  
•  InputStreamReader	
  has	
  methods	
  for	
  reading	
  one	
  
char	
  at	
  a	
  Kme	
  
•  We	
  don’t	
  want	
  to	
  read	
  one	
  char	
  at	
  a	
  .me	
  from	
  
user!	
  
Using	
  BufferedReader	
  
•  To	
  use	
  InputStreamReader	
  
–  BufferedReader a = new BufferedReader(new
InputStreamReader(System.in));
–  String mj = a.readLine();

•  Read	
  text	
  from	
  a	
  character-­‐input	
  stream,	
  
buffering	
  characters	
  so	
  as	
  to	
  provide	
  for	
  the	
  
efficient	
  reading	
  of	
  characters,	
  arrays,	
  and	
  
lines.	
  
Scanner	
  
•  Or	
  just	
  use	
  Scanner	
  from	
  Java	
  1.5!	
  
Scanner s = new Scanner(System.in);
String mj = s.nextLine();
READ	
  AND	
  WRITE	
  FILES	
  
Binary	
  vs	
  text	
  
•  All	
  data	
  are	
  in	
  the	
  end	
  binary:	
  
–  01010101001011100110	
  

•  Binary	
  files:	
  bits	
  represent	
  encoded	
  
informaKons,	
  executable	
  instrucKons	
  or	
  
numeric	
  data.	
  
•  Text	
  files:	
  the	
  binarys	
  represent	
  characters.	
  
Text	
  files	
  
•  In	
  text	
  files	
  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
Example	
  Encoding:	
  ASCII	
  
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	
  
•  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();
}
}
FileReader:	
  Reading	
  MulKple	
  Chars	
  
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");
int oneChar;
while ((oneChar = inputStream.read()) != -1) {
System.out.print((char) 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();
}
}
Buffering	
  
•  Using	
  unbuffered	
  IO	
  is	
  less	
  efficient	
  than	
  using	
  
buffered	
  IO.	
  
•  Read	
  stuff	
  to	
  buffer	
  in	
  memory	
  and	
  when	
  
buffer	
  is	
  full,	
  write	
  it.	
  Less	
  disk	
  access	
  or	
  
network	
  acKvity	
  
BufferedReader	
  
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,	
  BufferedWriter	
  
•  Convenient	
  way	
  of	
  wriKng	
  files	
  using	
  
PrintWriter:	
  
PrintWriter pw = new PrintWriter(
new BufferedWriter(
new FileWriter("output.txt")));
pw.println("hello!");
pw.close();
READING	
  AND	
  WRITING	
  BYTES	
  
Read	
  and	
  Write	
  
•  To	
  Read	
  
–  FileInputStream	
  

•  To	
  Write	
  
–  FileOutputStream	
  
Read	
  and	
  Write	
  
FileInputStream in = new FileInputStream("output.txt");
FileOutputStream out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
out.close();
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();
}
}
}
}
JAVA	
  7	
  NEW	
  FEATURES	
  
Java	
  7	
  to	
  the	
  rescue!	
  
How?	
  
•  Virtual	
  Machine	
  will	
  call	
  automaIcally	
  the	
  
close	
  method	
  upon	
  exiKng	
  the	
  try	
  block	
  (like	
  
finally)	
  
•  The	
  resource	
  object	
  must	
  implement	
  
AutoCloseable	
  interface	
  
•  The	
  interface	
  has	
  only	
  one	
  method:	
  close
•  If	
  closing	
  causes	
  excepKon,	
  it’s	
  suppressed	
  
(ignore).	
  Possible	
  to	
  get	
  it	
  using	
  
getSuppressed()	
  method	
  
Java	
  7	
  API	
  
API	
  Updates	
  to	
  File	
  System	
  
•  java.io	
  and	
  java.nio	
  are	
  updated	
  
•  Called	
  NIO.2	
  revision	
  
•  New	
  classes	
  (java.nio):	
  
–  Path	
  –	
  Locate	
  a	
  file	
  in	
  a	
  file	
  system	
  
•  Paths – Convert	
  a	
  URI	
  to	
  Path	
  object	
  

–  Files	
  –	
  Operate	
  on	
  files,	
  directories	
  and	
  other	
  
types	
  of	
  files	
  
–  FileVisitor	
  –	
  Traversing	
  files	
  in	
  a	
  tree	
  	
  
–  WatchService	
  –	
  File	
  change	
  modificaKon	
  API	
  
File	
  (Java	
  1.0	
  –	
  1.7)	
  
•  File	
  class	
  has	
  very	
  useful	
  methods:	
  
–  exists
–  canRead
–  canWrite
–  length
–  getPath

•  Example	
  
File f = new File(“file.txt”);
If(f.exists()) { .. }
java.nio.file.Path
•  Absolute	
  or	
  relaKve	
  path,	
  refers	
  to	
  files	
  in	
  file	
  system.	
  
•  Suppor&ng	
  API	
  to	
  java.io.File
•  File	
  to	
  Path:	
  
–  File f = new File(”/foo/bar/file.txt”);
–  Path p = f.toPath();

•  Path	
  to	
  File	
  
–  File f2 = p.toFile();

•  Path	
  is	
  an	
  interface!	
  InstanKaKng	
  using	
  either	
  File	
  or	
  or	
  
Paths	
  class	
  
–  Path p = Paths.get(“file.txt”);
Demo:	
  Path	
  -­‐	
  class	
  
java.nio.file.Files
•  Features	
  
–  Copy	
  
–  Create	
  directories	
  
–  Create	
  files	
  
–  Create	
  links	
  
–  Use	
  of	
  the	
  “temp”	
  –	
  folder	
  
–  Delete	
  
–  Adributes	
  –	
  Modified/Owner/Permission	
  
–  Read	
  /	
  Write	
  
java.nio.file.Files
•  StaKc	
  methods	
  for	
  reading,	
  wriKng	
  and	
  
manipulaKng	
  files	
  and	
  directories	
  
•  Files	
  uses	
  Path	
  objects!	
  
•  Methods	
  like	
  
–  createFile(Path p, ..);
–  delete(Path p);
–  move(…)
–  write(Path p, byte [] b, ..)
–  readAllLines(Path p, Charset cs)
Example	
  
Example	
  
SERIALIZATION	
  
Object	
  Streams	
  
•  To	
  read	
  and	
  write	
  objects!	
  
•  How?	
  
–  Object	
  class	
  must	
  implement	
  serializable	
  marker	
  
interface	
  
–  Read	
  and	
  write	
  using	
  ObjectInputStream	
  and	
  
ObjectOutputStream	
  

•  SerializaKon	
  is	
  used	
  in	
  Java	
  RMI	
  
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;
}
}
Example:	
  Saving	
  and	
  Reading	
  
// Save the object
fos = new FileOutputStream("car.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(datsun);
// Read the object
fis = new FileInputStream("car.dat");
ois = new ObjectInputStream(fis);
Car datsun2 = (Car) ois.readObject();
Transient	
  
•  Every	
  adribute	
  of	
  the	
  object	
  is	
  saved	
  into	
  
disk..	
  except	
  adribute	
  is	
  marked	
  with	
  
transient	
  keyword	
  
•  Mark	
  adributes	
  to	
  transient	
  when	
  the	
  
informaKon	
  is	
  secret	
  or	
  uneccessary.	
  
•  When	
  object	
  is	
  deserializaled,	
  transient	
  
adributes	
  values	
  are	
  null	
  
JAVA	
  NIO	
  
NIO:	
  High	
  performance	
  IO	
  
•  java.io	
  is	
  suitable	
  for	
  basic	
  needs.	
  When	
  there	
  
is	
  a	
  need	
  for	
  higher	
  performance,	
  use	
  Java	
  
NIO	
  (New	
  I/O)	
  (java.nio)	
  
•  Less	
  GC,	
  less	
  threads,	
  more	
  efficient	
  use	
  of	
  
operaKng	
  system	
  
•  Provides	
  scalable	
  I/O	
  operaKons	
  on	
  both	
  
binary	
  and	
  character	
  files.	
  Also	
  a	
  simple	
  
parsing	
  facility	
  based	
  on	
  regular	
  expressions	
  
•  A	
  lidle	
  bit	
  harder	
  to	
  use	
  than	
  java.io	
  
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	
  
Channels	
  and	
  Buffers	
  
•  Channels	
  are	
  what	
  streams	
  were	
  in	
  java.io	
  
•  All	
  data	
  transferred	
  in	
  java.nio	
  must	
  go	
  
through	
  a	
  Channel	
  
•  Buffer	
  is	
  a	
  container	
  object,	
  before	
  sending	
  
data	
  into	
  a	
  channel,	
  the	
  data	
  must	
  be	
  
wrapped	
  inside	
  a	
  Buffer	
  
•  Buffer	
  is	
  an	
  object,	
  which	
  holds	
  an	
  array	
  of	
  
bytes	
  
Buffer	
  Types	
  
•  There	
  are	
  many	
  classes	
  for	
  buffers.	
  These	
  classes	
  
inherit	
  java.nio.Buffer:	
  
•  ByteBuffer	
  -­‐	
  byte	
  array	
  
•  CharBuffer	
  
•  ShortBuffer	
  
•  IntBuffer	
  
•  LongBuffer	
  
•  FloatBuffer	
  
•  DoubleBuffer	
  
About	
  Channels	
  
•  You	
  never	
  write	
  a	
  byte	
  directly	
  into	
  a	
  channel.	
  
Bytes	
  must	
  be	
  wrapped	
  inside	
  a	
  buffer	
  
•  Channels	
  are	
  bi-­‐direcIonal	
  
•  Channels	
  can	
  be	
  opened	
  for	
  reading,	
  wriKng,	
  
or	
  both	
  
Example:	
  Reading	
  
FileInputStream	
  fin	
  =	
  new	
  FileInputStream(	
  "data.txt"	
  );	
  	
  
//	
  Get	
  a	
  channel	
  via	
  the	
  FileInputStream	
  
FileChannel	
  fc	
  	
  	
  	
  	
  	
  =	
  fin.getChannel();	
  	
  
//	
  Create	
  a	
  buffer	
  
ByteBuffer	
  buffer	
  	
  	
  =	
  ByteBuffer.allocate(	
  1024	
  );	
  
//	
  Read	
  from	
  channel	
  into	
  a	
  buffer	
  
fc.read(	
  buffer	
  );	
  	
  
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 );
Buffer	
  Internals	
  
•  Every	
  buffer	
  has	
  posiKon,	
  limit	
  and	
  capacity	
  
•  These	
  three	
  variables	
  track	
  the	
  state	
  of	
  the	
  buffer	
  
•  posiIon:	
  is	
  the	
  index	
  of	
  the	
  next	
  element	
  to	
  be	
  
read	
  or	
  wriden.	
  A	
  buffer's	
  posiKon	
  is	
  never	
  
negaKve	
  and	
  is	
  never	
  greater	
  than	
  its	
  limit.	
  
•  limit:	
  is	
  the	
  index	
  of	
  the	
  first	
  element	
  that	
  should	
  
not	
  be	
  read	
  or	
  wriden.	
  A	
  buffer's	
  limit	
  is	
  never	
  
negaKve	
  and	
  is	
  never	
  greater	
  than	
  its	
  capacity	
  
•  capacity:	
  is	
  the	
  number	
  of	
  elements	
  buffer	
  
contains.	
  The	
  capacity	
  of	
  a	
  buffer	
  is	
  never	
  
negaKve	
  and	
  never	
  changes.	
  
Buffer	
  Example	
  1	
  
Buffer	
  Example	
  2	
  
Buffer	
  Example	
  3	
  
Buffer	
  Example	
  4	
  
Buffer	
  Example	
  5	
  
Buffer	
  Example	
  6	
  
Buffer	
  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);
}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Files in java
Files in javaFiles in java
Files in java
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Applets
AppletsApplets
Applets
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Event handling
Event handlingEvent handling
Event handling
 
Java threads
Java threadsJava threads
Java threads
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Java swing
Java swingJava swing
Java swing
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 

Similar a Java I/O

L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with filesramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with fileskirupasuchi1996
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, SerializationPawanMM
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceanuvayalil5525
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 

Similar a Java I/O (20)

Java I/O
Java I/OJava I/O
Java I/O
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
05io
05io05io
05io
 
Files io
Files ioFiles io
Files io
 
JAVA
JAVAJAVA
JAVA
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
5java Io
5java Io5java Io
5java Io
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
Java
JavaJava
Java
 

Más de Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

Más de Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Último

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Java I/O

  • 1. Java  I/O   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. Intro   •  Input  /  Output   –  Input  from  file  or  keyboard   –  Output  to  screen  or  a  file   •  To  deliver  data,  stream  is  used  
  • 3. READ  AND  WRITE  CONSOLE  
  • 4. Read  and  Write  to  Console   •  Output  stream:   –  System.out   •  Input  Stream:   –  System.in  
  • 6. InputStream  (System.in)   Read  a  byte  from  user  input?  
  • 7. 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  specified   charset   •  InputStreamReader  has  methods  for  reading  one   char  at  a  Kme   •  We  don’t  want  to  read  one  char  at  a  .me  from   user!  
  • 8. Using  BufferedReader   •  To  use  InputStreamReader   –  BufferedReader a = new BufferedReader(new InputStreamReader(System.in)); –  String mj = a.readLine(); •  Read  text  from  a  character-­‐input  stream,   buffering  characters  so  as  to  provide  for  the   efficient  reading  of  characters,  arrays,  and   lines.  
  • 9. Scanner   •  Or  just  use  Scanner  from  Java  1.5!   Scanner s = new Scanner(System.in); String mj = s.nextLine();
  • 10. READ  AND  WRITE  FILES  
  • 11. Binary  vs  text   •  All  data  are  in  the  end  binary:   –  01010101001011100110   •  Binary  files:  bits  represent  encoded   informaKons,  executable  instrucKons  or   numeric  data.   •  Text  files:  the  binarys  represent  characters.  
  • 12. Text  files   •  In  text  files  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
  • 14. 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' } }
  • 15. Character  Streams   •  To  read  characters   –  FileReader •  To  write  characters   –  FileWriter
  • 16. 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(); } }
  • 17. FileReader:  Reading  MulKple  Chars   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"); int oneChar; while ((oneChar = inputStream.read()) != -1) { System.out.print((char) oneChar); } inputStream.close(); } }
  • 18. 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(); } }
  • 19. Buffering   •  Using  unbuffered  IO  is  less  efficient  than  using   buffered  IO.   •  Read  stuff  to  buffer  in  memory  and  when   buffer  is  full,  write  it.  Less  disk  access  or   network  acKvity  
  • 20. BufferedReader   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(); } }
  • 21. PrintWriter,  BufferedWriter   •  Convenient  way  of  wriKng  files  using   PrintWriter:   PrintWriter pw = new PrintWriter( new BufferedWriter( new FileWriter("output.txt"))); pw.println("hello!"); pw.close();
  • 23. Read  and  Write   •  To  Read   –  FileInputStream   •  To  Write   –  FileOutputStream  
  • 24. Read  and  Write   FileInputStream in = new FileInputStream("output.txt"); FileOutputStream out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close();
  • 26. 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(); } } } }
  • 27. JAVA  7  NEW  FEATURES  
  • 28. Java  7  to  the  rescue!  
  • 29. How?   •  Virtual  Machine  will  call  automaIcally  the   close  method  upon  exiKng  the  try  block  (like   finally)   •  The  resource  object  must  implement   AutoCloseable  interface   •  The  interface  has  only  one  method:  close •  If  closing  causes  excepKon,  it’s  suppressed   (ignore).  Possible  to  get  it  using   getSuppressed()  method  
  • 31. API  Updates  to  File  System   •  java.io  and  java.nio  are  updated   •  Called  NIO.2  revision   •  New  classes  (java.nio):   –  Path  –  Locate  a  file  in  a  file  system   •  Paths – Convert  a  URI  to  Path  object   –  Files  –  Operate  on  files,  directories  and  other   types  of  files   –  FileVisitor  –  Traversing  files  in  a  tree     –  WatchService  –  File  change  modificaKon  API  
  • 32. File  (Java  1.0  –  1.7)   •  File  class  has  very  useful  methods:   –  exists –  canRead –  canWrite –  length –  getPath •  Example   File f = new File(“file.txt”); If(f.exists()) { .. }
  • 33. java.nio.file.Path •  Absolute  or  relaKve  path,  refers  to  files  in  file  system.   •  Suppor&ng  API  to  java.io.File •  File  to  Path:   –  File f = new File(”/foo/bar/file.txt”); –  Path p = f.toPath(); •  Path  to  File   –  File f2 = p.toFile(); •  Path  is  an  interface!  InstanKaKng  using  either  File  or  or   Paths  class   –  Path p = Paths.get(“file.txt”);
  • 34. Demo:  Path  -­‐  class  
  • 35. java.nio.file.Files •  Features   –  Copy   –  Create  directories   –  Create  files   –  Create  links   –  Use  of  the  “temp”  –  folder   –  Delete   –  Adributes  –  Modified/Owner/Permission   –  Read  /  Write  
  • 36. java.nio.file.Files •  StaKc  methods  for  reading,  wriKng  and   manipulaKng  files  and  directories   •  Files  uses  Path  objects!   •  Methods  like   –  createFile(Path p, ..); –  delete(Path p); –  move(…) –  write(Path p, byte [] b, ..) –  readAllLines(Path p, Charset cs)
  • 40. Object  Streams   •  To  read  and  write  objects!   •  How?   –  Object  class  must  implement  serializable  marker   interface   –  Read  and  write  using  ObjectInputStream  and   ObjectOutputStream   •  SerializaKon  is  used  in  Java  RMI  
  • 41. 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; } }
  • 42. Example:  Saving  and  Reading   // Save the object fos = new FileOutputStream("car.dat"); oos = new ObjectOutputStream(fos); oos.writeObject(datsun); // Read the object fis = new FileInputStream("car.dat"); ois = new ObjectInputStream(fis); Car datsun2 = (Car) ois.readObject();
  • 43. Transient   •  Every  adribute  of  the  object  is  saved  into   disk..  except  adribute  is  marked  with   transient  keyword   •  Mark  adributes  to  transient  when  the   informaKon  is  secret  or  uneccessary.   •  When  object  is  deserializaled,  transient   adributes  values  are  null  
  • 45. NIO:  High  performance  IO   •  java.io  is  suitable  for  basic  needs.  When  there   is  a  need  for  higher  performance,  use  Java   NIO  (New  I/O)  (java.nio)   •  Less  GC,  less  threads,  more  efficient  use  of   operaKng  system   •  Provides  scalable  I/O  operaKons  on  both   binary  and  character  files.  Also  a  simple   parsing  facility  based  on  regular  expressions   •  A  lidle  bit  harder  to  use  than  java.io  
  • 46. 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  
  • 47. Channels  and  Buffers   •  Channels  are  what  streams  were  in  java.io   •  All  data  transferred  in  java.nio  must  go   through  a  Channel   •  Buffer  is  a  container  object,  before  sending   data  into  a  channel,  the  data  must  be   wrapped  inside  a  Buffer   •  Buffer  is  an  object,  which  holds  an  array  of   bytes  
  • 48. Buffer  Types   •  There  are  many  classes  for  buffers.  These  classes   inherit  java.nio.Buffer:   •  ByteBuffer  -­‐  byte  array   •  CharBuffer   •  ShortBuffer   •  IntBuffer   •  LongBuffer   •  FloatBuffer   •  DoubleBuffer  
  • 49. About  Channels   •  You  never  write  a  byte  directly  into  a  channel.   Bytes  must  be  wrapped  inside  a  buffer   •  Channels  are  bi-­‐direcIonal   •  Channels  can  be  opened  for  reading,  wriKng,   or  both  
  • 50. Example:  Reading   FileInputStream  fin  =  new  FileInputStream(  "data.txt"  );     //  Get  a  channel  via  the  FileInputStream   FileChannel  fc            =  fin.getChannel();     //  Create  a  buffer   ByteBuffer  buffer      =  ByteBuffer.allocate(  1024  );   //  Read  from  channel  into  a  buffer   fc.read(  buffer  );    
  • 51. 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 );
  • 52. Buffer  Internals   •  Every  buffer  has  posiKon,  limit  and  capacity   •  These  three  variables  track  the  state  of  the  buffer   •  posiIon:  is  the  index  of  the  next  element  to  be   read  or  wriden.  A  buffer's  posiKon  is  never   negaKve  and  is  never  greater  than  its  limit.   •  limit:  is  the  index  of  the  first  element  that  should   not  be  read  or  wriden.  A  buffer's  limit  is  never   negaKve  and  is  never  greater  than  its  capacity   •  capacity:  is  the  number  of  elements  buffer   contains.  The  capacity  of  a  buffer  is  never   negaKve  and  never  changes.  
  • 60. 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); }