Saturday, 9 March 2013

Byte Streams in Java

Background

We saw in last post in Java Tutorials section what streams in Java are.Byte stream is one of the type of streams used to perform 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. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Let us examine the way bytes streams are used by looking at an example -

Example code


public class ByteStreamDemonstrator {
    
    public static void main(String args[]) throws IOException
    {
        FileInputStream in = new FileInputStream(new File("inFile.txt"));
        FileOutputStream out = new FileOutputStream(new File("outFile.txt"));
        int c;
        
        while((c = in.read())!= -1)
        {
            out.write(c);
        }
        if(in!=null){
           in.close();
          }
        if(out!=null){     
           out.close();
          }
    }
}



Lets analyze the code now.


    We have define two byte streams FileInputStream in and FileOutputStream out.
Each stream take a File object as an input which in turn takes filename as an argument.Note that you can directly give filename as an argument to FileInputStream and FileOutputStream. Also note this filename is of type String.This file must be in your source directory, if not you can always give absolute path in the place of filename.
    In above code we have inFile and outFile as two files in src directory.We read from inFile and write to outFile.Note that read() function return an integer and when all data in input stream is read it will return -1 which can be used as a condition to terminate our loop.

Always close streams

   Never forget to close the streams you have opened. In above code we close the streams using .close() function. Note that we are checking if the stream is open or not before closing it because if due to some error stream was not opened and if we try closing it, it will throw runtime Exception. 


Better approach to write above code

    Above code is not the best way to write it.Since Exceptions are not explained yet above code will suffice our requirements in understanding byte stream.But the more correct approach to do above is put out reading/writing logic in try statement, catch the exception to handle the exceptions like FileNotFound Exception in catch block and use the Finally block to close the streams.

What is this throwing Exception?


   In above code observer the line throws IOException besides the main function.What it means that if there is any Exception just throw it (don't catch). Generally when a function throws an exception Exception is thrown to the function which has called the function throwing that Exception.The calling function must then either catch it and handle it or again throw it to it's parent function.

So what happens when every function throws the Exception and no one catches it?

   If no function catches the Exception it will finally come to the main() function.If even the main() function does not handle the Exception and just throws it like what we have done in above code then JVM will just shut down, terminating the program.Lets not worry about this at this point. We will cover this in much details when we learn about Exception handling.

When not to use byte stream?

    Since inFile and outFile contains characters the best way to do it is to use character stream which will be explained in our next post. Byte streams should only be used for primitive I/O.

So why talk about byte streams?

     Because all other stream types are built on byte streams. 

Related Links 

MCQ #5

Question) In switch construct , the default statement must be placed after all the case statements.

Options)

  • True
  • False
Answer) False

Explanation) Go through the Java tutorial on switch statement to know more about switch statement and it's usage.As for our question, default statement can be put anywhere in the switch construct but it will be called only when none of the other cases match. Also since default statement is the last one to be checked we need not even write break statement in default statement.So the answer is clearly False.

MCQ #4

Question) Member (instance) variables are always assigned a default value if not explicitly initialized.

Options)

  • True
  • False
Answer) True

Explanation) Go through the Java tutorial on Objects in java to know the difference between instance variables and local variables.As for our question, yes instance variables are assigned default values if not explicitly initialized.On the other hand compiler will complaint if local variables are used without initialization.

MCQ #3

Question)Assume x = 6 and y = 7 .What is the result of (!(y == x))

Options)

  • True
  • False
Answer) True

Explanation) The answer is pretty straight forward . x=6  and y=7 so y == x is false. Negation ( ! ) of false is true and hence our final result is True. Remember brackets have higher preference than any of the operators.

MCQ #2

Question) Using a break in a for loop causes the loop to break out of the current execution and jump to next iteration.

Options)
  • True
  • False
Answer) Flase

Explanation) I would recommend go through the post on Transfer Statements in Java Tutorials section.break keyword will cause loop to break out of current execution permanently and continue with the code after the loop.Note that break statement is used only in loops and switch statement.So answer is False.
t> UA-39527780-1 back to top