SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 

La actualidad más candente (20)

This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java IO
Java IOJava IO
Java IO
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Applets
AppletsApplets
Applets
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 

Destacado (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
 
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 a 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 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
 
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
 
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
 

Similar a 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
 

Más de Anton Keks

Más de 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
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

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