SlideShare a Scribd company logo
1 of 23
Download to read offline
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 (20)

javascript objects
javascript objectsjavascript objects
javascript objects
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java naming conventions
Java naming conventionsJava naming conventions
Java naming conventions
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Io streams
Io streamsIo streams
Io streams
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
java-thread
java-threadjava-thread
java-thread
 
Java String
Java StringJava String
Java String
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java collections
Java collectionsJava collections
Java collections
 

Viewers also liked

Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1CAVC
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion controlShubham Jain
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 

Viewers also liked (12)

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
 
14 file handling
14 file handling14 file handling
14 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

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 5Akshay 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 5Akshay 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.pptxYashrajMohrir
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
File handling in input and output
File handling in input and outputFile handling in input and output
File handling in input and outputpradeepa velmurugan
 
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 & Outputphanleson
 
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, 11Ivelin Yanev
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter 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_2016Manuel Fomitescu
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton 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 testerAnton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton 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 & ServletsAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton 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 & EncodingsAnton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to AgileAnton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsAnton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton 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, HibernateAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton 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 engineerAnton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software DeveloperAnton 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

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

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