I/O Handling in Java

How Java handles input from the user and output from the system to user? Java do I/O(Input/Output) through streams.

Now what all Streams Java can have are following:
1. ByteStreams for I/O of bytes(binary data)
2. Character Streams for I/O of characters
3. Buffered Streams for optimizing I/O process by using concept of buffers.
4. Scanning & Formatting for reading and writing of formatted text
5. I/O from CommandLine using Console
6. DataStreams for binar I/O of primitive data types as well as Strings
7. ObjectStreams handle I/O of objects.

Now each of them will be discussed programs wise in detail in my next posts over here but before that for clearing up your theoretical concepts you can refer following link. Very good link.
#-Link-Snipped-#

Any doubts related to this topic only feel free to ask in this thread only.


[ Note: File Handling will be discussed in separate thread. ]

EDIT: Please check references used #-Link-Snipped-#

PS: @Mods Please check if any illegal link is shared over here.

Replies

  • shalini_goel14
    shalini_goel14
    Byte Streams in Java

    [Byte Streams in Java]

    There is quite a long list of Byte Stream Classes provided in Java but at the top are two abstract classes InputStream and OutputStream, rest all are concrete classes. Now you might be thinking what are abstract classes and concrete classes. No need to worry , I will discuss that in a separate thread. For now information abstract classes use the keyword abstract in their declaration and those classes can never be instantiated.

    Methods that are commonly used by InputStream are following:
    void close() - closes the input source.

    int read() - returns an integer representation of the next available byte of input. When -1 is returned , it indicates the end of the file.

    int read(byte buffer[]) - attempts to read up to buffer.length bytes into buffer and returns the actual no of bytes that were successfully read.

    Methods that are commonly used by OutputStream are following:
    void close() - closes the output stream.

    void flush()- it flushes the output buffer.

    void write(int b) - writes a single byte to an output stream.

    void write(byte buffer[]) - writes a complete array of bytes to an output stream.

    There are many bytestream classes available in Java and all are descendants of InputStream and OutputStream Classes. Like ByteArrayInputStream , ByteArrayOutputStream, FileInputStream, FileOutputStream, FilterInputStream, AudioInputStream, SequenceInputStream etc.

    But here I will show you program only for FileInputStream and FileOutputStream. Rest are not commonly used but yes you all can try them out also.

    Look at the following ByteStreamExample program
    package myjava;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     *
     * @author shalinig
     */
    public class ByteStreamExample {
    
        public static void main(String[] args) throws IOException{
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream("C:/My Input Files/FileInputStreamText.txt");
                out = new FileOutputStream("C:/My Output Files/FileOutputStreamText.txt");
                int c;
    
                while ((c = in.read()) != -1) {
                    out.write(c);
    
                }
    
            } catch (FileNotFoundException e) {
                System.out.println("Exception caused : File Not Found");
            } catch (IOException e) {
                System.out.println("IO Exception caused");
            } finally {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        }
    }
    
    Before running this program in your system, make sure you have created 1 FileInputStreamText.txt at specified location in your system (C:/My Input Files/) and some text is written in it. For me right now text in this txt file is:
    Hello ! I am a Crazy Computer Engineer . Testing Byte Stream Program.​
    Also an empty file FileOutputStreamText.txt at specified location in your system (C:/My Output Files/) and no text is written in it.

    Now when you will run thisprogram , you will see that text from input file gets written in output file.So now your output text file will show following text ​
    Hello ! I am a Crazy Computer Engineer . Testing Byte Stream Program.​
    Any questions regarding program. Feel free to ask. 😀​

    Please wait, soon all type of stream classes will be covered.​

    [Note: Exception Handling, if you don't know, no need to worry , it wil also be covered soon in separate thread.]​
  • shalini_goel14
    shalini_goel14
    Character Streams in Java

    [Character Streams in Java ]
    Just like Byte Stream , there are lot of Character Stream classes and at the top are two abstract classes - Reader and Writer and rest are the descendants of these two classes

    Methods that are commonly used by Reader class are following

    abstract void close()- Closes the input source.

    int read() - returns an integer representation of the next available character from the invoking input stream. When -1 is returned , it indicates the end of the file.

    int read(char buffer[]) attempts to read up to buffer.length characters into buffer and returns the actual no of characters that were successfully read. When -1 is returned , it indicates the end of the file.

    Methods that are commonly used by Writer class are following

    abstract void close()- Closes the output stream.

    abstract void flush()- Flushes the output buffers.

    void write(int ch) - Writes a single character to the invoking output stream.

    void write(char buffer[]) Writes a complete array of characters to the invoking output stream.

    There are many Character Stream classes in Java and all are descendants of Reader and Writer. Few of them are CharArrayReader, CharArrayWriter, FileReader, FileWriter , FilterReader, FilterWriter, PipedReader, PipedWriter, InputStreamReader, OutputStreamWriter, StringReader, StringWriter etc.

    But here I will show you program for commonly used FileReader and FileWriter classes. Rest you all try (if any one following or reading this 😁 )

    Writing a simple program using FileReader and FileWriter is very much similar to program I showed using FileInputStream and FileOutputStream. See the following program.

    package myjava;
    
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    /**
     *
     * @author shalinig
     */
    public class CharacterStreamExample {
    public static void main(String[] args) throws IOException{
            FileReader fr = null;
            FileWriter fw = null;
            try {
                fr = new FileReader("C:/My Input Files/FileReaderText.txt");
                fw = new FileWriter("C:/My Output Files/FileWriterText.txt");
                int c;
    
                while ((c = fr.read()) != -1) {
                    fw.write(c);
    
                }
    
            } catch (FileNotFoundException e) {
                System.out.println("Exception caused : File Not Found");
            } catch (IOException e) {
                System.out.println("IO Exception caused");
            } finally {
                if (fr != null) {
                    fr.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }
    
    Before running this program in your system, make sure you have created 1 FileReaderText.txt at specified location in your system (C:/My Input Files/) and some text is written in it. For me right now text in this txt file is:

    Hello ! I am a Crazy Computer Engineer . Testing Character Stream Program.
    Also an empty file FileWriterText.txt at specified location in your system (C:/My Output Files/) and no text is written in it.

    Hello ! I am a Crazy Computer Engineer . Testing Character Stream Program.

    Now when you will run thisprogram , you will see that text from input file gets written in output file.So now your output text file will show following text ​

    Any questions regarding program. Feel free to ask.Keep on exploring other Character Stream Classes 😀​
  • shalini_goel14
    shalini_goel14
    Buffered Streams in Java

    [Buffered Streams]

    Buffered Streams classes are made just to make lower level classes like FileInputStream, FileOutputStream,FileReader, FileWriter (as discussed in last two posts) more efficient and easier to use. They read(or write) large chunks of data from(or to) a file at once and keep this in a buffer which minimizes the no of times that file read(or write).

    Now there are 4 Buffered Stream Classes
    1. BufferedInputStream -allows to wrap any InputStream into a buffered stream and achieve its performance improvement. Support same methods as that of InputStream classes.

    2. BufferedOutputStream-similar to OutputStream only with buffer facility but flush() method works differently in this it ensures that data in buffer is written to the output device before clearing up the buffer.

    3. BufferedReader - similar to FileReader with buffer facility. Provides an additional readLine() method that allows us to get the next line of characters from a file.

    4. BufferedWriter - similar ro FileWriter with buffer faciltiy and also provide an additional newLine() method that makes it easy to create platform- specific line separators automatically.

    Below is the program showing usage of BufferedInputStream and BufferedOutputStream

    package myjava;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     *
     * @author shalinig
     */
    public class BufferedByteStreamExample {
    
        public static void main(String[] args) throws IOException {
            FileInputStream in = null;
            FileOutputStream out = null;
            BufferedInputStream bin = null;
            BufferedOutputStream bout = null;
            try {
                in = new FileInputStream("C:/My Input Files/BufferedInputStreamText.txt");
                out = new FileOutputStream("C:/My Output Files/BufferedOutputStreamText.txt");
    
                bin = new BufferedInputStream(in);
                bout = new BufferedOutputStream(out);
    
                int c;
                
                while ((c = bin.read()) != -1) {
                    bout.write(c);
                }
                
            } catch (FileNotFoundException e) {
                System.out.println("Exception caused : File Not Found");
            } catch (IOException e) {
                System.out.println("IO Exception caused");
            } finally {
                if (bin != null) {
                    bin.close();
                }
                if (bout != null) {
                    bout.close();
                }
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        }
    
    
    }
    
    Before running the above program in your system, make sure you have created 1 BufferedInputStreamText.txt at specified location in your system (C:/My Input Files/) and some text is written in it. For me right now text in this txt file is:
    Hello ! I am a Crazy Computer Engineer .Testing Buffered Byte Stream Program.
    The same text gets printed in BufferedOutputStreamText.txt file at C:/My Output Files location.



    Below is the program for BufferedReader and BufferedWriter

    package myjava;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    /**
     *
     * @author shalinig
     */
    public class BufferedCharacterStreamExample {
    public static void main(String[] args) throws IOException {
            FileReader fr = null;
            FileWriter fw = null;
            BufferedReader br = null;
            BufferedWriter bw = null;
            try {
                fr = new FileReader("C:/My Input Files/BufferedReaderText.txt");
                fw = new FileWriter("C:/My Output Files/BufferedWriterText.txt");
    
                br = new BufferedReader(fr);
                bw = new BufferedWriter(fw);
    
                String s;
    
                while ((s = br.readLine()) != null) {
                    bw.append(s);
                    bw.newLine();
                }
                
            } catch (FileNotFoundException e) {
                System.out.println("Exception caused : File Not Found");
            } catch (IOException e) {
                System.out.println("IO Exception caused");
            } finally {
                 if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
                 if (fr != null) {
                    fr.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }
    
    Before running the above program in your system, make sure you have created 1 BufferedReaderText.txt at specified location in your system (C:/My Input Files/) and some text is written in it. For me right now text in this txt file is:
    Hello ! I am a Crazy Computer Engineer .
    Testing Buffered Character Stream Program.
    The same text gets printed in BufferedWriterText.txt file at C:/My Output Files location.

    [Note: Please make sure in finally() block , your buffered output stream object(bout and bw) should be closed before input stream object (out and fw) ]

You are reading an archived discussion.

Related Posts

Paceman RP Singh was on Monday rewarded for his consistent performance in the ongoing IPL with a recall while fellow speedster Munaf Patel was dropped from India's 15-member squad for...
i have been hooked for hours on a programmer but cant get it to work....if i set the configwords setting off, then its k....how does one know which settings to...
Hi , My first post. Can someone suggest me a book on application of computer programming in field of mech engg. specifically automobile industry.
Its very good puzzle. It is simple but still its effective to confuse peple to scratch her heads. Here is the puzzle: We have total 100 rs and we need...
This thread is dedicated for automation concepts and problems you faced during automation with various tools. Be it a Open source or its a paid tool, do post your quires....