SlideShare uma empresa Scribd logo
1 de 76
Baixar para ler offline
Java I/O Stream


                  1
Topics
●   What is an I/O stream?
●   Types of Streams
●   Stream class hierarchy
●   Control flow of an I/O operation using Streams
●   Byte streams
●   Character streams
●   Buffered streams
●   Standard I/O streams
●   Data streams
●   Object streams
●   File class
                                                     2
What is an I/O
  Stream?
                 3
I/O Streams
●   An I/O Stream represents an input source or an
    output destination
●   A stream can represent many different kinds of
    sources and destinations
    –   disk files, devices, other programs, a network
        socket, and memory arrays
●   Streams support many different kinds of data
    –   simple bytes, primitive data types, localized
        characters, and objects
●   Some streams simply pass on data; others
    manipulate and transform the data in useful ways.
                                                         4
I/O Streams
●   No matter how they work internally, all streams
    present the same simple model to programs that
    use them
    –   A stream is a sequence of data




                                                      5
Input Stream
●   A program uses an input stream to read data from
    a source, one item at a time




                                                             6
                                       source:java.sun.com
Output Stream
●   A program uses an output stream to write data to a
    destination, one item at time




                                                         7
Types of Streams

                   8
General Stream Types
●   Character and Byte Streams
    –   Character vs. Byte
●   Input and Output Streams
    –   Based on source or destination
●   Node and Filter Streams
    –   Whether the data on a stream is manipulated or
        transformed or not




                                                         9
Character and Byte Streams
●   Byte streams
    –   For binary data
    –   Root classes for byte streams:
         ●   The InputStream Class
         ●   The OutputStream Class
         ●   Both classes are abstract
●   Character streams
    –   For Unicode characters
    –   Root classes for character streams:
         ●   The Reader class
         ●   The Writer class
         ●   Both classes are abstract        10
Input and Output Streams
●   Input or source streams
    –   Can read from these streams
    –   Root classes of all input streams:
         ●   The InputStream Class
         ●   The Reader Class
●   Output or sink (destination) streams
    –   Can write to these streams
    –   Root classes of all output streams:
         ●   The OutputStream Class
         ●   The Writer Class

                                              11
Node and Filter Streams
●   Node streams (Data sink stream)
    –   Contain the basic functionality of reading or writing
        from a specific location
    –   Types of node streams include files, memory and
        pipes
●   Filter streams (Processing stream)
    –   Layered onto node streams between threads or
        processes
    –   For additional functionality- altering or managing
        data in the stream
●   Adding layers to a node stream is called stream
    chaining                                                    12
Stream Class
 Hierarchy
               13
Streams
InputStream



OutputStream



Reader


Writer




               14
Abstract Classes
●   InputStream & OutputStream
●   Reader & Writer




                                 15
InputStream Abstract Class




                             16
InputStream Abstract Class




                             17
Node InputStream Classes




                           18
Filter InputStream Classes




                             19
OutputStream Abstract Class




                              20
Node OutputStream Classes




                            21
Filter OutputStream Classes




                              22
The Reader Class: Methods




                            23
The Reader Class: Methods




                            24
Node Reader Classes




                      25
Filter Reader Classes




                        26
The Writer Class: Methods




                            27
Node Writer Classes




                      28
Filter Writer Classes




                        29
Control Flow of
I/O Operation using
     Streams
                      30
Control Flow of an I/O operation
Create a stream object and associate it with a data-
  source (data-destination)
Give the stream object the desired functionality
  through stream chaining
while (there is more information)
   read(write) next data from(to) the stream
close the stream




                                                       31
Byte Stream

              32
Byte Stream
●   Programs use byte streams to perform input and
    output of 8-bit bytes
●   All byte stream classes are descended from
    InputStream and OutputStream
●   There are many byte stream classes
    –   FileInputStream and FileOutputStream
●   They are used in much the same way; they differ
    mainly in the way they are constructed



                                                      33
When Not to Use Byte Streams?
●   Byte Stream represents a kind of low-level I/O that
    you should avoid
    –   If the data contains character data, the best
        approach is to use character streams
    –   There are also streams for more complicated data
        types
●   Byte streams should only be used for the most
    primitive I/O
●   All other streams are based on byte stream


                                                           34
Example: FileInputStream &
          FileOutputStream
public class CopyBytes {
  public static void main(String[] args) throws IOException {
     FileInputStream in = null;
     FileOutputStream out = null;
     try {
        in = new FileInputStream("xanadu.txt");
        out = new FileOutputStream("outagain.txt");
        int c;

       while ((c = in.read()) != -1) {
         out.write(c);
       }
     }
     // More code
                                                                35
Example: FileInputStream &
             FileOutputStream
        finally {
           if (in != null) {
               in.close();
           }
           if (out != null) {
               out.close();
           }
        }
    }
}




                                      36
Simple Byte Stream input and
           output




                               37
Character Stream

                   38
Character Stream
●   The Java platform stores character values using
    Unicode conventions
●   Character stream I/O automatically translates this
    internal format to and from the local character set.
    –   In Western locales, the local character set is usually
        an 8-bit superset of ASCII.
●   All character stream classes are descended from
    Reader and Writer
●   As with byte streams, there are character stream
    classes that specialize in file I/O: FileReader and
    FileWriter.
                                                                 39
Character Stream
●   For most applications, I/O with character streams is
    no more complicated than I/O with byte streams.
    –   Input and output done with stream classes
        automatically translates to and from the local
        character set.
    –   A program that uses character streams in place of
        byte streams automatically adapts to the local
        character set and is ready for internationalization —
        all without extra effort by the programmer.
    –   If internationalization isn't a priority, you can simply
        use the character stream classes without paying
        much attention to character set issues.
    –   Later, if internationalization becomes a priority, your
        program can be adapted without extensive recoding. 40
Example: FileReader & FileWriter
public class CopyCharacters {
  public static void main(String[] args) throws IOException {
     FileReader inputStream = null;
     FileWriter outputStream = null;

     try {
        inputStream = new FileReader("xanadu.txt");
        outputStream = new FileWriter("characteroutput.txt");

       int c;
       while ((c = inputStream.read()) != -1) {
          outputStream.write(c);
       }
     }
     // More code                                               41
Example: FileReader & FileWriter
        finally {
           if (inputStream != null) {
               inputStream.close();
           }
           if (outputStream != null) {
               outputStream.close();
           }
        }
    }
}




                                         42
Character Stream and Byte Stream
●   Character streams are often "wrappers" for byte
    streams
●   The character stream uses the byte stream to
    perform the physical I/O, while the character stream
    handles translation between characters and bytes.
    –   FileReader, for example, uses FileInputStream,
        while FileWriter uses FileOutputStream




                                                           43
Line-Oriented I/O
●   Character I/O usually occurs in bigger units than
    single characters
     – One common unit is the line: a string of
       characters with a line terminator at the end
    –   A line terminator can be a carriage-return/line-
        feed sequence ("rn"), a single carriage-return
        ("r"), or a single line-feed ("n").




                                                           44
Example: Line-oriented I/O
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");

FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);

BufferedReader inputStream = new BufferedReader(in);
PrintWriter outputStream = new PrintWriter(out);

String l;
while ((l = inputStream.readLine()) != null) {
   System.out.println(l);
   outputStream.println(l);
}

in.close();                                            45
out.close();
Buffered Stream

                  46
Why Buffered Streams?
●   An unbuffered I/O means each read or write
    request is handled directly by the underlying OS
    –   This can make a program much less efficient, since
        each such request often triggers disk access,
        network activity, or some other operation that is
        relatively expensive.
●   To reduce this kind of overhead, the Java platform
    implements buffered I/O streams
    –   Buffered input streams read data from a memory
        area known as a buffer; the native input API is called
        only when the buffer is empty
    –   Similarly, buffered output streams write data to a
        buffer, and the native output API is called only when
        the buffer is full.                                      47
How to create Buffered Streams?
●   A program can convert a unbuffered stream into a
    buffered stream using the wrapping idiom
    –   A unbuffered stream object is passed to the constructor
        for a buffered stream class
●   Example
        inputStream =
          new BufferedReader(new FileReader("xanadu.txt"));
        outputStream =
          new BufferedWriter(new FileWriter("characteroutput.txt"));


                                                                       48
Buffered Stream Classes
●   BufferedInputStream and BufferedOutputStream
    create buffered byte streams
●   BufferedReader and BufferedWriter create buffered
    character streams




                                                        49
Flushing Buffered Streams
●   It often makes sense to write out a buffer at critical
    points, without waiting for it to fill. This is known as
    flushing the buffer.
●   Some buffered output classes support autoflush,
    specified by an optional constructor argument.
     –   When autoflush is enabled, certain key events cause
         the buffer to be flushed
     –   For example, an autoflush PrintWriter object flushes
         the buffer on every invocation of println or format.
●   To flush a stream manually, invoke its flush method
     –   The flush method is valid on any output stream, but
         has no effect unless the stream is buffered.           50
Standard Streams

                   51
Standard Streams on Java Platform
●   Three standard streams
    –   Standard Input, accessed through System.in
    –   Standard Output, accessed through System.out
    –   Standard Error, accessed through System.err
●   These objects are defined automatically and do not
    need to be opened
●   System.out and System.err are defined as
    PrintStream objects



                                                         52
Data Streams

               53
Data Streams
●   Data streams support binary I/O of primitive data
    type values (boolean, char, byte, short, int, long,
    float, and double) as well as String values
●   All data streams implement either the DataInput
    interface or the DataOutput interface
●   DataInputStream and DataOutputStream are most
    widely-used implementations of these interfaces




                                                          54
DataOutputStream
●   DataOutputStream can only be created as a wrapper
    for an existing byte stream object
       out = new DataOutputStream(
              new BufferedOutputStream(
              new FileOutputStream(dataFile)));
       for (int i = 0; i < prices.length; i ++) {
          out.writeDouble(prices[i]);
          out.writeInt(units[i]);
          out.writeUTF(descs[i]);
       }

                                                        55
DataInputStream
●   Like DataOutputStream, DataInputStream must be
    constructed as a wrapper for a byte stream
●   End-of-file condition is detected by catching
    EOFException, instead of testing for an invalid return
    value
        in = new DataInputStream(
             new BufferedInputStream(
             new FileInputStream(dataFile)));

        try{
            double price = in.readDouble();
            int unit = in.readInt();
            String desc = in.readUTF();
        } catch (EOFException e){
        }
                                                             56
Object Streams

                 57
Object Streams
●   Object streams support I/O of objects
    –   Like Data streams support I/O of primitive data types
    –   The object has to be Serializable type
●   The object stream classes are ObjectInputStream
    and ObjectOutputStream
    –   These classes implement ObjectInput and
        ObjectOutput, which are subinterfaces of DataInput
        and DataOutput
    –   An object stream can contain a mixture of primitive
        and object values

                                                                58
Input and Output of Complex
                   Object
●   The writeObject and readObject methods are
    simple to use, but they contain some very
    sophisticated object management logic
    –   This isn't important for a class like Calendar, which
        just encapsulates primitive values. But many objects
        contain references to other objects.
●   If readObject is to reconstitute an object from a
    stream, it has to be able to reconstitute all of the
    objects the original object referred to.
    –   These additional objects might have their own
        references, and so on.
                                                                59
WriteObject
●   The writeObject traverses the entire web of object
    references and writes all objects in that web onto
    the stream
●   A single invocation of writeObject can cause a large
    number of objects to be written to the stream.




                                                           60
I/O of multiple referred-to objects
●   Object a contains references to objects b and c,
    while b contains references to d and e




                                                       61
I/O of multiple referred-to objects
●   Invoking writeObject(a) writes not just a, but all the
    objects necessary to reconstitute a, so the other
    four objects in this web are written also
●   When a is read back by readObject, the other four
    objects are read back as well, and all the original
    object references are preserved.




                                                             62
Closing Streams

                  63
Always Close Streams
●   Closing a stream when it's no longer needed is very
    important — so important that your program should
    use a finally block to guarantee that both streams
    will be closed even if an error occurs
    –   This practice helps avoid serious resource leaks.




                                                            64
File Class

             65
The File Class
●   Not a stream class
●   Important since stream classes manipulate File
    objects
●   Abstract representation of actual files and directory
    pathname




                                                            66
The File Class: Constructors
●   Has four constructors




                                     67
The File Class: Methods




                          68
The File Class: Methods




                          69
The File Class: Example
1    import java.io.*;
2

3    public class FileInfoClass {
4       public static void main(String args[]) {
5          String fileName = args[0];
6          File fn = new File(fileName);
7          System.out.println("Name: " + fn.getName());
8          if (!fn.exists()) {
9             System.out.println(fileName
10                               + " does not exists.");
11   //continued...

                                                           70
The File Class: Example
12   /* Create a temporary directory instead. */
13   System.out.println("Creating temp directory...");
14   fileName = "temp";
15   fn = new File(fileName);
16   fn.mkdir();
17   System.out.println(fileName +
18       (fn.exists()? "exists": "does not exist"));
19   System.out.println("Deleting temp directory...");
20   fn.delete();
21   //continued...



                                                       71
The File Class: Example
24

25         System.out.println(fileName + " is a " +
26                     (fn.isFile()? "file." :"directory."));
27

28         if (fn.isDirectory()) {
29             String content[] = fn.list();
30             System.out.println("The content of this directory:
43             for (int i = 0; i < content.length; i++) {
44                 System.out.println(content[i]);
45             }
46         }
35
                                                            72
36   //continued...
The File Class: Example
36

37

38         if (!fn.canRead()) {
39             System.out.println(fileName
40                                + " is not readable.");
41             return;
42         }
43   //continued...




                                                            73
The File Class: Example
47           System.out.println(fileName + " is " + fn.length()
48                              + " bytes long.");
49           System.out.println(fileName + " is " +
50                         fn.lastModified() + " bytes long.");
51

52           if (!fn.canWrite()) {
53               System.out.println(fileName
54                                   + " is not writable.");
55           }
56       }
57   }

                                                               74
Modified InputStream/
             OutputStream Example
24           } catch (IOException ie) {
25               ie.printStackTrace();
26           }
27       }
28

29       public static void main(String args[]) {
30           String inputFile = args[0];
31           CopyFile cf = new CopyFile();
32           cf.copy(inputFile);
33       }
34   }


                                                    75
Thank You!



             76

Mais conteúdo relacionado

Mais procurados

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52myrajendra
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49myrajendra
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51myrajendra
 
IO and serialization
IO and serializationIO and serialization
IO and serializationbackdoor
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Filesprimeteacher32
 
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
 

Mais procurados (19)

Java Streams
Java StreamsJava Streams
Java Streams
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java stream
Java streamJava stream
Java stream
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
 
Files in java
Files in javaFiles in java
Files in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
 
Java IO
Java IOJava IO
Java IO
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
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
 

Destaque

Destaque (10)

Ese Neno Da Rua
Ese Neno Da RuaEse Neno Da Rua
Ese Neno Da Rua
 
Xen Directions HXEN Slides
Xen Directions HXEN SlidesXen Directions HXEN Slides
Xen Directions HXEN Slides
 
Apollotheme presentation
Apollotheme presentationApollotheme presentation
Apollotheme presentation
 
XS Oracle 2009 Error Detection
XS Oracle 2009 Error DetectionXS Oracle 2009 Error Detection
XS Oracle 2009 Error Detection
 
XS Oracle 2009 Networking 10gig
XS Oracle 2009 Networking 10gigXS Oracle 2009 Networking 10gig
XS Oracle 2009 Networking 10gig
 
XS Japan 2008 Ganeti English
XS Japan 2008 Ganeti EnglishXS Japan 2008 Ganeti English
XS Japan 2008 Ganeti English
 
XS Boston 2008 Guest Spinning
XS Boston 2008 Guest SpinningXS Boston 2008 Guest Spinning
XS Boston 2008 Guest Spinning
 
XS Boston 2008 Paravirt Ops in Linux IA64
XS Boston 2008 Paravirt Ops in Linux IA64XS Boston 2008 Paravirt Ops in Linux IA64
XS Boston 2008 Paravirt Ops in Linux IA64
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Ian Pratt Usenix 08 Keynote
Ian Pratt Usenix 08 KeynoteIan Pratt Usenix 08 Keynote
Ian Pratt Usenix 08 Keynote
 

Semelhante a Javaiostream

CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxnoonoboom
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfhemanth248901
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptxssuser9d7049
 
Java session14
Java session14Java session14
Java session14Niit Care
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in javaJyoti Verma
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesSakkaravarthiS1
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2Gera Paulos
 

Semelhante a Javaiostream (20)

Io streams
Io streamsIo streams
Io streams
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Java session14
Java session14Java session14
Java session14
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
Chapter 2.1 : Data Stream
Chapter 2.1 : Data StreamChapter 2.1 : Data Stream
Chapter 2.1 : Data Stream
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Basic IO
Basic IOBasic IO
Basic IO
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
Java I/O
Java I/OJava I/O
Java I/O
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
Io stream
Io streamIo stream
Io stream
 

Último

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 

Último (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 

Javaiostream

  • 2. Topics ● What is an I/O stream? ● Types of Streams ● Stream class hierarchy ● Control flow of an I/O operation using Streams ● Byte streams ● Character streams ● Buffered streams ● Standard I/O streams ● Data streams ● Object streams ● File class 2
  • 3. What is an I/O Stream? 3
  • 4. I/O Streams ● An I/O Stream represents an input source or an output destination ● A stream can represent many different kinds of sources and destinations – disk files, devices, other programs, a network socket, and memory arrays ● Streams support many different kinds of data – simple bytes, primitive data types, localized characters, and objects ● Some streams simply pass on data; others manipulate and transform the data in useful ways. 4
  • 5. I/O Streams ● No matter how they work internally, all streams present the same simple model to programs that use them – A stream is a sequence of data 5
  • 6. Input Stream ● A program uses an input stream to read data from a source, one item at a time 6 source:java.sun.com
  • 7. Output Stream ● A program uses an output stream to write data to a destination, one item at time 7
  • 9. General Stream Types ● Character and Byte Streams – Character vs. Byte ● Input and Output Streams – Based on source or destination ● Node and Filter Streams – Whether the data on a stream is manipulated or transformed or not 9
  • 10. Character and Byte Streams ● Byte streams – For binary data – Root classes for byte streams: ● The InputStream Class ● The OutputStream Class ● Both classes are abstract ● Character streams – For Unicode characters – Root classes for character streams: ● The Reader class ● The Writer class ● Both classes are abstract 10
  • 11. Input and Output Streams ● Input or source streams – Can read from these streams – Root classes of all input streams: ● The InputStream Class ● The Reader Class ● Output or sink (destination) streams – Can write to these streams – Root classes of all output streams: ● The OutputStream Class ● The Writer Class 11
  • 12. Node and Filter Streams ● Node streams (Data sink stream) – Contain the basic functionality of reading or writing from a specific location – Types of node streams include files, memory and pipes ● Filter streams (Processing stream) – Layered onto node streams between threads or processes – For additional functionality- altering or managing data in the stream ● Adding layers to a node stream is called stream chaining 12
  • 15. Abstract Classes ● InputStream & OutputStream ● Reader & Writer 15
  • 23. The Reader Class: Methods 23
  • 24. The Reader Class: Methods 24
  • 27. The Writer Class: Methods 27
  • 30. Control Flow of I/O Operation using Streams 30
  • 31. Control Flow of an I/O operation Create a stream object and associate it with a data- source (data-destination) Give the stream object the desired functionality through stream chaining while (there is more information) read(write) next data from(to) the stream close the stream 31
  • 33. Byte Stream ● Programs use byte streams to perform input and output of 8-bit bytes ● All byte stream classes are descended from InputStream and OutputStream ● There are many byte stream classes – FileInputStream and FileOutputStream ● They are used in much the same way; they differ mainly in the way they are constructed 33
  • 34. When Not to Use Byte Streams? ● Byte Stream represents a kind of low-level I/O that you should avoid – If the data contains character data, the best approach is to use character streams – There are also streams for more complicated data types ● Byte streams should only be used for the most primitive I/O ● All other streams are based on byte stream 34
  • 35. Example: FileInputStream & FileOutputStream public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } // More code 35
  • 36. Example: FileInputStream & FileOutputStream finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } 36
  • 37. Simple Byte Stream input and output 37
  • 39. Character Stream ● The Java platform stores character values using Unicode conventions ● Character stream I/O automatically translates this internal format to and from the local character set. – In Western locales, the local character set is usually an 8-bit superset of ASCII. ● All character stream classes are descended from Reader and Writer ● As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. 39
  • 40. Character Stream ● For most applications, I/O with character streams is no more complicated than I/O with byte streams. – Input and output done with stream classes automatically translates to and from the local character set. – A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer. – If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. – Later, if internationalization becomes a priority, your program can be adapted without extensive recoding. 40
  • 41. Example: FileReader & FileWriter public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } // More code 41
  • 42. Example: FileReader & FileWriter finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } 42
  • 43. Character Stream and Byte Stream ● Character streams are often "wrappers" for byte streams ● The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. – FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream 43
  • 44. Line-Oriented I/O ● Character I/O usually occurs in bigger units than single characters – One common unit is the line: a string of characters with a line terminator at the end – A line terminator can be a carriage-return/line- feed sequence ("rn"), a single carriage-return ("r"), or a single line-feed ("n"). 44
  • 45. Example: Line-oriented I/O File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); BufferedReader inputStream = new BufferedReader(in); PrintWriter outputStream = new PrintWriter(out); String l; while ((l = inputStream.readLine()) != null) { System.out.println(l); outputStream.println(l); } in.close(); 45 out.close();
  • 47. Why Buffered Streams? ● An unbuffered I/O means each read or write request is handled directly by the underlying OS – This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. ● To reduce this kind of overhead, the Java platform implements buffered I/O streams – Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty – Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. 47
  • 48. How to create Buffered Streams? ● A program can convert a unbuffered stream into a buffered stream using the wrapping idiom – A unbuffered stream object is passed to the constructor for a buffered stream class ● Example inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt")); 48
  • 49. Buffered Stream Classes ● BufferedInputStream and BufferedOutputStream create buffered byte streams ● BufferedReader and BufferedWriter create buffered character streams 49
  • 50. Flushing Buffered Streams ● It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. ● Some buffered output classes support autoflush, specified by an optional constructor argument. – When autoflush is enabled, certain key events cause the buffer to be flushed – For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. ● To flush a stream manually, invoke its flush method – The flush method is valid on any output stream, but has no effect unless the stream is buffered. 50
  • 52. Standard Streams on Java Platform ● Three standard streams – Standard Input, accessed through System.in – Standard Output, accessed through System.out – Standard Error, accessed through System.err ● These objects are defined automatically and do not need to be opened ● System.out and System.err are defined as PrintStream objects 52
  • 54. Data Streams ● Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values ● All data streams implement either the DataInput interface or the DataOutput interface ● DataInputStream and DataOutputStream are most widely-used implementations of these interfaces 54
  • 55. DataOutputStream ● DataOutputStream can only be created as a wrapper for an existing byte stream object out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(dataFile))); for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]); } 55
  • 56. DataInputStream ● Like DataOutputStream, DataInputStream must be constructed as a wrapper for a byte stream ● End-of-file condition is detected by catching EOFException, instead of testing for an invalid return value in = new DataInputStream( new BufferedInputStream( new FileInputStream(dataFile))); try{ double price = in.readDouble(); int unit = in.readInt(); String desc = in.readUTF(); } catch (EOFException e){ } 56
  • 58. Object Streams ● Object streams support I/O of objects – Like Data streams support I/O of primitive data types – The object has to be Serializable type ● The object stream classes are ObjectInputStream and ObjectOutputStream – These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput – An object stream can contain a mixture of primitive and object values 58
  • 59. Input and Output of Complex Object ● The writeObject and readObject methods are simple to use, but they contain some very sophisticated object management logic – This isn't important for a class like Calendar, which just encapsulates primitive values. But many objects contain references to other objects. ● If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to. – These additional objects might have their own references, and so on. 59
  • 60. WriteObject ● The writeObject traverses the entire web of object references and writes all objects in that web onto the stream ● A single invocation of writeObject can cause a large number of objects to be written to the stream. 60
  • 61. I/O of multiple referred-to objects ● Object a contains references to objects b and c, while b contains references to d and e 61
  • 62. I/O of multiple referred-to objects ● Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this web are written also ● When a is read back by readObject, the other four objects are read back as well, and all the original object references are preserved. 62
  • 64. Always Close Streams ● Closing a stream when it's no longer needed is very important — so important that your program should use a finally block to guarantee that both streams will be closed even if an error occurs – This practice helps avoid serious resource leaks. 64
  • 66. The File Class ● Not a stream class ● Important since stream classes manipulate File objects ● Abstract representation of actual files and directory pathname 66
  • 67. The File Class: Constructors ● Has four constructors 67
  • 68. The File Class: Methods 68
  • 69. The File Class: Methods 69
  • 70. The File Class: Example 1 import java.io.*; 2 3 public class FileInfoClass { 4 public static void main(String args[]) { 5 String fileName = args[0]; 6 File fn = new File(fileName); 7 System.out.println("Name: " + fn.getName()); 8 if (!fn.exists()) { 9 System.out.println(fileName 10 + " does not exists."); 11 //continued... 70
  • 71. The File Class: Example 12 /* Create a temporary directory instead. */ 13 System.out.println("Creating temp directory..."); 14 fileName = "temp"; 15 fn = new File(fileName); 16 fn.mkdir(); 17 System.out.println(fileName + 18 (fn.exists()? "exists": "does not exist")); 19 System.out.println("Deleting temp directory..."); 20 fn.delete(); 21 //continued... 71
  • 72. The File Class: Example 24 25 System.out.println(fileName + " is a " + 26 (fn.isFile()? "file." :"directory.")); 27 28 if (fn.isDirectory()) { 29 String content[] = fn.list(); 30 System.out.println("The content of this directory: 43 for (int i = 0; i < content.length; i++) { 44 System.out.println(content[i]); 45 } 46 } 35 72 36 //continued...
  • 73. The File Class: Example 36 37 38 if (!fn.canRead()) { 39 System.out.println(fileName 40 + " is not readable."); 41 return; 42 } 43 //continued... 73
  • 74. The File Class: Example 47 System.out.println(fileName + " is " + fn.length() 48 + " bytes long."); 49 System.out.println(fileName + " is " + 50 fn.lastModified() + " bytes long."); 51 52 if (!fn.canWrite()) { 53 System.out.println(fileName 54 + " is not writable."); 55 } 56 } 57 } 74
  • 75. Modified InputStream/ OutputStream Example 24 } catch (IOException ie) { 25 ie.printStackTrace(); 26 } 27 } 28 29 public static void main(String args[]) { 30 String inputFile = args[0]; 31 CopyFile cf = new CopyFile(); 32 cf.copy(inputFile); 33 } 34 } 75