SlideShare a Scribd company logo
Java course - IAG0040




             I/O, Files & Streams




Anton Keks                             2011
File System
 ●
     java.io.File provides system-independent view of
     hierarchical pathnames (immutable)
     –   File f = new File(“/bin”);
         f = new File(f, “ping”);
 ●
     Can be used to represent files or directories
     –   check for existence and permissions
     –   query various info (length, attributes)
     –   Create, rename or delete both files and directories
     –   static fields provide quick access to system-dependent
         separators: File.separator, File.pathSeparator
     –   '/' works on all platforms, including Windows
Java course – IAG0040                                          Lecture 8
Anton Keks                                                       Slide 2
File System Tips
 ●   How to avoid dealing with separators
      –   File parent = new File(“someDir”);
      –   File subdir = new File(parent, “bin”);
 ●   Obtain a valid temporary file
      –   File tmpFile = File.createTempFile(“something”, “.tmp”);
      –   tmpFile.deleteOnExit();
 ●
     Enumerate Windows drives
      –   File[] roots = File.listRoots();
      –   File unixRoot = roots[0];
 ●
     Enumerate files in a directory
      –   File[] files = new File(“someDir”).listFiles();

Java course – IAG0040                                       Lecture 8
Anton Keks                                                    Slide 3
Random Access
 ●
     java.io.RandomAccessFile
     –   is used when streams are not suitable, e.g. random access
         of large binary files
     –   like a large array of bytes in the file system
     –   both reading and writing is possible (depending on mode)
 ●   Has a file pointer that can be read and moved
     –   getFilePointer(), seek()
 ●
     Reading/writing methods are very similar to various
     Input/OuputStreams
     –   even DataInput and DataOutput are implemented

Java course – IAG0040                                        Lecture 8
Anton Keks                                                     Slide 4
I/O as Streams




Java course – IAG0040                    Lecture 8
Anton Keks                                 Slide 5
I/O and Streams
 ●
     Java provides I/O facilities in 2 packages
     –   java.io – traditional synchronous stream-based I/O
     –   java.nio – 'new' (a)synchronous block-based I/O
 ●   I/O is about reading and writing data
 ●
     Reading and writing is possible using Streams
     –   Streams are processed sequentially
     –   Streams are independent of nature of data
 ●
     Java provides two types (hierarchies) of Streams
     –   Byte streams (binary)
     –   Character streams (unicode text)
Java course – IAG0040                                         Lecture 8
Anton Keks                                                      Slide 6
Basic Stream processing
 Reading                      Writing
 ●
     open a stream            ●
                                  open a stream
     (defines the source)         (defines the destination)
 ●
     while more information   ●
                                  while more information
     –   read information         –   write information
 ●
     close the stream         ●
                                  close the stream

 Provided by:                 Provided by:
 ●
     java.io.InputStream      ●
                                  java.io.OutputStream
 ●
     java.io.Reader           ●
                                  java.io.Writer
Java course – IAG0040                                 Lecture 8
Anton Keks                                              Slide 7
Basic operations
 ●
     Reader and InputStream
     –   int read() - reads a single byte/character (returned as int)
     –   int read(byte/char buf[]) - reads as many bytes as possible into
         the passed array, returns number of bytes read
     –   int read(byte/char buf[], int offset, int length) - the
         same, but works with the specified portion of an array
     –   In addition, both support marking locations within a stream, skipping
         input data, and resetting current position
 ●
     Writer and OutputStream
     –   void write(...) methods are analogous with reading
     –   void flush() - flushes all buffered data to the output (if any)


Java course – IAG0040                                                   Lecture 8
Anton Keks                                                                Slide 8
Opening and Closing
 ●
     Streams are automatically opened on creation
     –   If you have a stream instance – it is ready for reading or writing
 ●
     Closing is explicit
     –   close() method closes the stream
     –   flush() is implicit during closing of output streams
     –   Frees all underlying resources
     –   Is not the same as object destruction
     –   Always call it as early as possible
     –   After close() is called, any reads or writes will fail
     –   Closing several times is safe

Java course – IAG0040                                                Lecture 8
Anton Keks                                                             Slide 9
IOException
 ●
     I/O classes throw checked IOExceptions
 ●   Used by both java.io and java.nio
 ●   There are many more specific derived
     exceptions, like FileNotFoundException,
     EOFException, CharacterCodingException, etc
 ●   Even the close() method can throw an
     IOException (unfortunately)
           –   Leads to TCFTC (try-catch-finally-try-catch)


Java course – IAG0040                                    Lecture 8
Anton Keks                                                Slide 10
Stream classification
 ●
     Direction: input and output
 ●
     Data type: binary and character
 ●
     Sink streams or 'endpoints'
      –   FileInputStream, ByteArrayInputStream, StringReader, etc
 ●   Processing streams (wrappers)
      –   Base classes: FilterInputStream, FilterOutputStream,
          FilterReader, FilterWriter
      –   SequenceInputStream, ObjectInputStream,
          BufferedInputStream, LineNumberReader, etc
 ●   Bridges from binary to characters
      –   InputStreamReader, OutputStreamWriter
Java course – IAG0040                                            Lecture 8
Anton Keks                                                        Slide 11
In-memory I/O
 ●
     These streams operate on in-memory data
     structures, which are passed to them on
     creation
     –   ByteArrayInputStream, ByteArrayOutputStream
     –   CharArrayReader, CharArrayWriter
     –   StringReader, StringWriter
     –   StringBufferInputStream (deprecated)
 ●
     Useful for mocking streams


Java course – IAG0040                            Lecture 8
Anton Keks                                        Slide 12
File I/O
 ●
     Reading files
     –   FileInputStream – reads binary files
     –   FileReader – reads text files using the default encoding
          ●
           InputStreamReader can be used for other encodings
 ●
     Writing files
     –   FileOutputStream – writes binary files
     –   FileWriter – writes text files using the default encoding
 ●
     Task:
     –   write a simple 'copy' program (SimpleCopyProgram
         class), implement net.azib.java.lessons.io.FileCopier
Java course – IAG0040                                      Lecture 8
Anton Keks                                                  Slide 13
Buffering
 ●   These streams wrap other streams to provide
     buffering capabilities
     –   BufferedInputStream, PushbackInputStream
     –   BufferedOutputStream
     –   BufferedReader, PushbackReader
     –   BufferedWriter
 ●   Task:
     –   write BufferedCopyProgram (implementing FileCopier)
     –   measure performance of both implementations with
         System.currentTimeMillis()
Java course – IAG0040                                   Lecture 8
Anton Keks                                               Slide 14
Formatted printing
 ●
     Provide convenient printing (e.g. to the console, file, another
     Writer, or OutputStream)
 ●   Write-only
      –   PrintWriter (is preferred)
      –   PrintStream (System.out and System.err)
 ●
     Often other writable streams are wrapped into these
 ●
     They do internal buffering, either a newline char or special
     method invocations automatically flush the data in case
     autoFlush is enabled
 ●
     Warning: IOExceptions are never thrown out!
      –   checkError() may be used for error checking
Java course – IAG0040                                         Lecture 8
Anton Keks                                                     Slide 15
Misc features
●
     Concatenation:
      –   SequenceInputStream – allows to concatenate multiple InputStreams together
●    Pipes:
      –   PipedInputStream, PipedOutputStream, PipedReader, PipedWriter – allows to
          connect InputStream to an OutputStream
●    Counting:
      –   LineNumberReader – counts line numbers while reading
●    Peeking ahead:
      –   PushbackInputStream and PushbackReader – allows to return read data back to
          stream
●    Arbitrary data:
      –   DataInputStream, DataOutputStream – allows to read/write primitive types easily

    Java course – IAG0040                                                    Lecture 8
    Anton Keks                                                                Slide 16
Serialization
●   Java natively supports serialization of data (persistent storage of objects'
    internal state)
     –   Serialization: ObjectOutputStream
     –   Deserealization: ObjectInputStream
●   Interfaces
     –   Serializable – marker but has some methods documented
     –   Externalizable – defines methods for saving/restoring data manually
         during the serialization
●   It is highly recommended to define static final long
    serialVersionUID field in serializable classes (used for compatibility
    checks), otherwise it is computed automatically
●   fields, declared as transient or static, are not serialized
●   Can be used for deep cloning, faster than cloning recursively
Java course – IAG0040                                                     Lecture 8
Anton Keks                                                                 Slide 17
Channels and Buffers
●
    java.nio offers a new way for I/O: Channels and
    Buffers
    –   All data operations are performed on Buffers (data blocks)
         ●   There are buffers for all primitive types, like
             ByteBuffer, LongBuffer, FloatBuffer, etc
         ●
             Buffers are allocated using their static methods
         ●
             Buffers are internally arrays, which maintain their
             capacity, limit, and position, thus simplifying writing
             code
    –   Channels are like Streams, but they are bi-directional and
        read or write data from/into Buffers only. No direct access
        to data is possible.
                                                                 Lecture 8
                                                                  Slide 18
Buffers
●   All buffers are mutable
●
    ByteBuffer is most used, provides methods for reading/writing all
    other primitive types, absolute (index-based) and relative (current
    position based)
●
    ByteBuffer provides views as other buffers, e.g. IntBuffer,
    FloatBuffer
●
    Direct buffers are backed by OS native storage if possible, non-
    direct buffers are Java arrays
       ByteBuffer.allocate() - allocates a non-direct buffer
       ByteBuffer.allocateDirect() - allocates a direct buffer
       ByteBuffer.wrap() - wraps an existing Java array
    clear() prepares buffer for reading (discards previous content)
    flip() prepares buffer for writing after it was used for reading

                                                                  Lecture 8
                                                                   Slide 19
Channels
●   A channel is an open connection used for
    reading/writing of data contained in Buffers
●   Channels static class provides utility methods for
    bridging java.io Streams and java.nio Channels
●   ReadableByteChannel, WritebleByteChannel, and
    ByteChannel operate on ByteBuffers
●   ScatteringByteChannel and GatheringByteChannel
    operate on arrays of buffers (useful when reading
    fixed length heterogeneous data sequentially)


                                                   Lecture 8
                                                    Slide 20
FileChannel
●   Can be obtained with getChannel() either from
    FileInputStream, FileOutputStream, or
    RandomAccessFile (read-only, write-only, and read-
    write respectively)
●
    Provides file locking and file portion locking with
    lock() methods
●   Provides memory mapping with map() methods
    –   Memory mapped I/O maps files (whole or in parts) directly
        to the memory to speed up random reads/writes
●   “Advanced” features depend on the support from the
    underlying OS
                                                           Lecture 8
                                                            Slide 21
Channels and Buffers Task
●   Write some more 'copy' functionality
     –   With non-direct buffer
     –   With direct buffer
     –   With memory-mapped I/O
●   Measure performance of these and the ones written before
     –   Stream based
     –   Buffered stream based
●
    Implement everything as implementing the FileCopier interface
●   Input file, output file, and copying method should be specifiable on
    the command-line
●   Write unit tests (you can use File.createTempFile() method)
                                                                 Lecture 8
                                                                  Slide 22
Asynchronous I/O
●   java.nio provides APIs for asynchronous I/O
     –   All other I/O in Java is synchronous (blocking)
●
    Channels, extending the abstract SelectableChannel, can work
    asynchronously
●   Selector is a multiplexor, obtained using Selector.open()
●   SelectionKey represents a SelectableChannel's registration with a
    Selector
●   SelectableChannel provides several register() methods for
    registering itself with a Selector for particular events
     –   configureBlocking() is used for enabling asynchronous
         mode
●   selector.select() is then used for waiting for registered events
                                                                 Lecture 8
                                                                  Slide 23

More Related Content

What's hot

Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
atozknowledge .com
 
File handling
File handlingFile handling
File handling
priya_trehan
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
Spotle.ai
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
Files in java
Files in javaFiles in java
Java Collections
Java  Collections Java  Collections
Threads in JAVA
Threads in JAVAThreads in JAVA
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
Abhilash Nair
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 

What's hot (20)

Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
 
File handling
File handlingFile handling
File handling
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java Streams
Java StreamsJava Streams
Java Streams
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Files in java
Files in javaFiles in java
Files in java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
14 file handling
14 file handling14 file handling
14 file handling
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 

Viewers also liked

Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
Amandeep Kaur
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1
CAVC
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Congestion control in TCP
Congestion control in TCPCongestion control in TCP
Congestion control in TCP
selvakumar_b1985
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
Avinash Varma Kalidindi
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
Shubham Jain
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Socket programming
Socket programmingSocket programming
Socket programming
chandramouligunnemeda
 

Viewers also liked (11)

Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Congestion control in TCP
Congestion control in TCPCongestion control in TCP
Congestion control in TCP
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Socket programming
Socket programmingSocket programming
Socket programming
 

Similar to Java Course 8: I/O, Files and Streams

Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
JAVA
JAVAJAVA
05io
05io05io
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
Akshay Nagpurkar
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
Akshay Nagpurkar
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
YashrajMohrir
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
Boulder Java User's Group
 
File handling in input and output
File handling in input and outputFile handling in input and output
File handling in input and output
pradeepa velmurugan
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Manav Prasad
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
Ivelin Yanev
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
Tien Nguyen
 
javaiostream
javaiostreamjavaiostream
javaiostream
Arjun Shanka
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
kanchanmahajan23
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016
Manuel Fomitescu
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 

Similar to Java Course 8: I/O, Files and Streams (20)

Java I/O
Java I/OJava I/O
Java I/O
 
JAVA
JAVAJAVA
JAVA
 
05io
05io05io
05io
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
File handling in input and output
File handling in input and outputFile handling in input and output
File handling in input and output
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
Anton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
Anton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
Anton Keks
 

More from Anton Keks (18)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
Priyanka Aash
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
ankush9927
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
Matthias Neugebauer
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
Shiv Technolabs
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
Brian Pichman
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
shanihomely
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
BrainSell Technologies
 
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
Priyanka Aash
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 

Recently uploaded (20)

How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
 
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 

Java Course 8: I/O, Files and Streams

  • 1. Java course - IAG0040 I/O, Files & Streams Anton Keks 2011
  • 2. File System ● java.io.File provides system-independent view of hierarchical pathnames (immutable) – File f = new File(“/bin”); f = new File(f, “ping”); ● Can be used to represent files or directories – check for existence and permissions – query various info (length, attributes) – Create, rename or delete both files and directories – static fields provide quick access to system-dependent separators: File.separator, File.pathSeparator – '/' works on all platforms, including Windows Java course – IAG0040 Lecture 8 Anton Keks Slide 2
  • 3. File System Tips ● How to avoid dealing with separators – File parent = new File(“someDir”); – File subdir = new File(parent, “bin”); ● Obtain a valid temporary file – File tmpFile = File.createTempFile(“something”, “.tmp”); – tmpFile.deleteOnExit(); ● Enumerate Windows drives – File[] roots = File.listRoots(); – File unixRoot = roots[0]; ● Enumerate files in a directory – File[] files = new File(“someDir”).listFiles(); Java course – IAG0040 Lecture 8 Anton Keks Slide 3
  • 4. Random Access ● java.io.RandomAccessFile – is used when streams are not suitable, e.g. random access of large binary files – like a large array of bytes in the file system – both reading and writing is possible (depending on mode) ● Has a file pointer that can be read and moved – getFilePointer(), seek() ● Reading/writing methods are very similar to various Input/OuputStreams – even DataInput and DataOutput are implemented Java course – IAG0040 Lecture 8 Anton Keks Slide 4
  • 5. I/O as Streams Java course – IAG0040 Lecture 8 Anton Keks Slide 5
  • 6. I/O and Streams ● Java provides I/O facilities in 2 packages – java.io – traditional synchronous stream-based I/O – java.nio – 'new' (a)synchronous block-based I/O ● I/O is about reading and writing data ● Reading and writing is possible using Streams – Streams are processed sequentially – Streams are independent of nature of data ● Java provides two types (hierarchies) of Streams – Byte streams (binary) – Character streams (unicode text) Java course – IAG0040 Lecture 8 Anton Keks Slide 6
  • 7. Basic Stream processing Reading Writing ● open a stream ● open a stream (defines the source) (defines the destination) ● while more information ● while more information – read information – write information ● close the stream ● close the stream Provided by: Provided by: ● java.io.InputStream ● java.io.OutputStream ● java.io.Reader ● java.io.Writer Java course – IAG0040 Lecture 8 Anton Keks Slide 7
  • 8. Basic operations ● Reader and InputStream – int read() - reads a single byte/character (returned as int) – int read(byte/char buf[]) - reads as many bytes as possible into the passed array, returns number of bytes read – int read(byte/char buf[], int offset, int length) - the same, but works with the specified portion of an array – In addition, both support marking locations within a stream, skipping input data, and resetting current position ● Writer and OutputStream – void write(...) methods are analogous with reading – void flush() - flushes all buffered data to the output (if any) Java course – IAG0040 Lecture 8 Anton Keks Slide 8
  • 9. Opening and Closing ● Streams are automatically opened on creation – If you have a stream instance – it is ready for reading or writing ● Closing is explicit – close() method closes the stream – flush() is implicit during closing of output streams – Frees all underlying resources – Is not the same as object destruction – Always call it as early as possible – After close() is called, any reads or writes will fail – Closing several times is safe Java course – IAG0040 Lecture 8 Anton Keks Slide 9
  • 10. IOException ● I/O classes throw checked IOExceptions ● Used by both java.io and java.nio ● There are many more specific derived exceptions, like FileNotFoundException, EOFException, CharacterCodingException, etc ● Even the close() method can throw an IOException (unfortunately) – Leads to TCFTC (try-catch-finally-try-catch) Java course – IAG0040 Lecture 8 Anton Keks Slide 10
  • 11. Stream classification ● Direction: input and output ● Data type: binary and character ● Sink streams or 'endpoints' – FileInputStream, ByteArrayInputStream, StringReader, etc ● Processing streams (wrappers) – Base classes: FilterInputStream, FilterOutputStream, FilterReader, FilterWriter – SequenceInputStream, ObjectInputStream, BufferedInputStream, LineNumberReader, etc ● Bridges from binary to characters – InputStreamReader, OutputStreamWriter Java course – IAG0040 Lecture 8 Anton Keks Slide 11
  • 12. In-memory I/O ● These streams operate on in-memory data structures, which are passed to them on creation – ByteArrayInputStream, ByteArrayOutputStream – CharArrayReader, CharArrayWriter – StringReader, StringWriter – StringBufferInputStream (deprecated) ● Useful for mocking streams Java course – IAG0040 Lecture 8 Anton Keks Slide 12
  • 13. File I/O ● Reading files – FileInputStream – reads binary files – FileReader – reads text files using the default encoding ● InputStreamReader can be used for other encodings ● Writing files – FileOutputStream – writes binary files – FileWriter – writes text files using the default encoding ● Task: – write a simple 'copy' program (SimpleCopyProgram class), implement net.azib.java.lessons.io.FileCopier Java course – IAG0040 Lecture 8 Anton Keks Slide 13
  • 14. Buffering ● These streams wrap other streams to provide buffering capabilities – BufferedInputStream, PushbackInputStream – BufferedOutputStream – BufferedReader, PushbackReader – BufferedWriter ● Task: – write BufferedCopyProgram (implementing FileCopier) – measure performance of both implementations with System.currentTimeMillis() Java course – IAG0040 Lecture 8 Anton Keks Slide 14
  • 15. Formatted printing ● Provide convenient printing (e.g. to the console, file, another Writer, or OutputStream) ● Write-only – PrintWriter (is preferred) – PrintStream (System.out and System.err) ● Often other writable streams are wrapped into these ● They do internal buffering, either a newline char or special method invocations automatically flush the data in case autoFlush is enabled ● Warning: IOExceptions are never thrown out! – checkError() may be used for error checking Java course – IAG0040 Lecture 8 Anton Keks Slide 15
  • 16. Misc features ● Concatenation: – SequenceInputStream – allows to concatenate multiple InputStreams together ● Pipes: – PipedInputStream, PipedOutputStream, PipedReader, PipedWriter – allows to connect InputStream to an OutputStream ● Counting: – LineNumberReader – counts line numbers while reading ● Peeking ahead: – PushbackInputStream and PushbackReader – allows to return read data back to stream ● Arbitrary data: – DataInputStream, DataOutputStream – allows to read/write primitive types easily Java course – IAG0040 Lecture 8 Anton Keks Slide 16
  • 17. Serialization ● Java natively supports serialization of data (persistent storage of objects' internal state) – Serialization: ObjectOutputStream – Deserealization: ObjectInputStream ● Interfaces – Serializable – marker but has some methods documented – Externalizable – defines methods for saving/restoring data manually during the serialization ● It is highly recommended to define static final long serialVersionUID field in serializable classes (used for compatibility checks), otherwise it is computed automatically ● fields, declared as transient or static, are not serialized ● Can be used for deep cloning, faster than cloning recursively Java course – IAG0040 Lecture 8 Anton Keks Slide 17
  • 18. Channels and Buffers ● java.nio offers a new way for I/O: Channels and Buffers – All data operations are performed on Buffers (data blocks) ● There are buffers for all primitive types, like ByteBuffer, LongBuffer, FloatBuffer, etc ● Buffers are allocated using their static methods ● Buffers are internally arrays, which maintain their capacity, limit, and position, thus simplifying writing code – Channels are like Streams, but they are bi-directional and read or write data from/into Buffers only. No direct access to data is possible. Lecture 8 Slide 18
  • 19. Buffers ● All buffers are mutable ● ByteBuffer is most used, provides methods for reading/writing all other primitive types, absolute (index-based) and relative (current position based) ● ByteBuffer provides views as other buffers, e.g. IntBuffer, FloatBuffer ● Direct buffers are backed by OS native storage if possible, non- direct buffers are Java arrays ByteBuffer.allocate() - allocates a non-direct buffer ByteBuffer.allocateDirect() - allocates a direct buffer ByteBuffer.wrap() - wraps an existing Java array clear() prepares buffer for reading (discards previous content) flip() prepares buffer for writing after it was used for reading Lecture 8 Slide 19
  • 20. Channels ● A channel is an open connection used for reading/writing of data contained in Buffers ● Channels static class provides utility methods for bridging java.io Streams and java.nio Channels ● ReadableByteChannel, WritebleByteChannel, and ByteChannel operate on ByteBuffers ● ScatteringByteChannel and GatheringByteChannel operate on arrays of buffers (useful when reading fixed length heterogeneous data sequentially) Lecture 8 Slide 20
  • 21. FileChannel ● Can be obtained with getChannel() either from FileInputStream, FileOutputStream, or RandomAccessFile (read-only, write-only, and read- write respectively) ● Provides file locking and file portion locking with lock() methods ● Provides memory mapping with map() methods – Memory mapped I/O maps files (whole or in parts) directly to the memory to speed up random reads/writes ● “Advanced” features depend on the support from the underlying OS Lecture 8 Slide 21
  • 22. Channels and Buffers Task ● Write some more 'copy' functionality – With non-direct buffer – With direct buffer – With memory-mapped I/O ● Measure performance of these and the ones written before – Stream based – Buffered stream based ● Implement everything as implementing the FileCopier interface ● Input file, output file, and copying method should be specifiable on the command-line ● Write unit tests (you can use File.createTempFile() method) Lecture 8 Slide 22
  • 23. Asynchronous I/O ● java.nio provides APIs for asynchronous I/O – All other I/O in Java is synchronous (blocking) ● Channels, extending the abstract SelectableChannel, can work asynchronously ● Selector is a multiplexor, obtained using Selector.open() ● SelectionKey represents a SelectableChannel's registration with a Selector ● SelectableChannel provides several register() methods for registering itself with a Selector for particular events – configureBlocking() is used for enabling asynchronous mode ● selector.select() is then used for waiting for registered events Lecture 8 Slide 23