I/O
Interview Questions
1.What do you understand by an IO stream?
-
The stream is a sequence of data that flows from source to destination.
-
It is composed of bytes.
-
In Java, three streams are created for us automatically.
- System.out: standard output stream
- System.in: standard input stream
- System.err: standard error stream
🔔Note
OutputStream vs InputStream
1)OutputStream
Java application uses an output stream
to write data to a destination; it may be a file, an array, peripheral device or socket.
2)InputStream
Java application uses an input stream
to read data from a source; it may be a file, an array, peripheral device or socket.
OutputStream class vs InputStream class
1)OutputStream class
- OutputStream class is an abstract class.
- It is the superclass of all classes representing an output stream of bytes.
- An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream
Method | Description |
---|---|
1) public void write(int)throws IOException | is used to write a byte to the current output stream. |
2) public void write(byte[])throws IOException | is used to write an array of byte to the current output stream. |
3) public void flush()throws IOException | flushes the current output stream. |
4) public void close()throws IOException | is used to close the current output stream. |
OutputStream Hierarchy
2)InputStream class
- InputStream class is an abstract class.
- It is the superclass of all classes representing an input stream of bytes.
Useful methods of InputStream
Method | Description |
---|---|
1) public abstract int read()throws IOException | reads the next byte of data from the input stream. It returns -1 at the end of the file. |
2) public int available()throws IOException | returns an estimate of the number of bytes that can be read from the current input stream. |
3) public void close()throws IOException | is used to close the current input stream. |
InputStream Hierarchy
2.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
- The Reader/Writer class hierarchy is
character-oriented
, and the InputStream/OutputStream class hierarchy isbyte-oriented
. - The ByteStream classes are used to perform input-output of
8-bit bytes
whereas the CharacterStream classes are used to perform the input/output for the16-bit Unicode system
. - There are many classes in the
ByteStream class hierarchy
, but the most frequently used classes areFileInputStream and FileOutputStream
. - The most frequently used classes
CharacterStream class hierarchy
isFileReader and FileWriter
.
3.What are the super most classes for all the streams?
- All the stream classes can be divided into two types of classes that are
ByteStream classes
andCharacterStream Classes
. - The ByteStream classes are further divided into
InputStream classes
andOutputStream classes
. CharacterStream classes
are also divided intoReader classes
andWriter classes
.- The SuperMost classes for all the
InputStream classes
isjava.io.InputStream
and for all theoutput stream classes
isjava.io.OutPutStream
. - Similarly, for all the
reader classes
, the super-most class isjava.io.Reader
, and for all thewriter classes
, it isjava.io.Writer
.
4.What are the FileInputStream and FileOutputStream?
FileOutputStream
- Java FileOutputStream is an output stream used for writing data to a file.
- If you have some primitive values to write into a file, use FileOutputStream class.
- You can write byte-oriented as well as character-oriented data through the FileOutputStream class.
- However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
public class A{
public static void main(String args[]){
try{
FileOutputStream test=new FileOutputStream("C:\\projects\\a.txt");
test.write(65);
test.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
success...
FileInputStream
- Java FileInputStream class obtains input bytes from a file.
- It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc.
- You can also read character-stream data.
- However, for reading streams of characters, it is recommended to use FileReader class.
public class A{
public static void main(String args[]){
try{
FileInputStream test=new FileInputStream("C:\\projects\\a.txt");
int i=test.read();
System.out.println((char)i);
test.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
A
success...
5. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?
- Java BufferedOutputStream class is used for buffering an output stream.
- It internally uses a buffer to store data.
- It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
- Whereas, Java BufferedInputStream class is used to read information from the stream.
6.How to set the Permissions to a file in Java?
- In Java,
FilePermission class
is used to alter the permissions set on a file. - Java FilePermission class contains the permission related to a directory or file. All the permissions are related to the path.
The path can be of two types:
- D:\IO\-:
It indicates that the permission is associated with all subdirectories and files recursively. - D:\IO\*:
It indicates that the permission is associated with all directory and files within this directory excluding subdirectories.
public class A{
public static void main(String[] args) throws IOException {
String srg = "C:\\IO projects\\a.txt";
FilePermission file1 = new FilePermission("C:\\IO projects\\-", "read");
PermissionCollection permission = file1.newPermissionCollection();
permission.add(file1);
FilePermission file2 = new FilePermission(srg, "write");
permission.add(file2);
if(permission.implies(new FilePermission(srg, "read,write"))) {
System.out.println("Read, Write permission is granted for the path "+srg );
}else {
System.out.println("No Read, Write permission is granted for the path "+srg);
}
}
}
Read, Write permission is granted for the path C:\IO projects\a.txt
7.What are FilterStreams?
FilterStream classes
are used to add additional functionalities to the other stream classes.- FilterStream classes act like an interface which read the data from a stream, filters it, and pass the filtered data to the caller.
- The FilterStream classes provide extra functionalities like adding line numbers to the destination file, etc.
8.What is an I/O filter?
- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
- Many Filter classes that allow a user to make a chain using multiple input streams. It generates a combined effect on several filters
9.In Java, How many ways you can take input from the console?
3 ways by using
- Using BufferedReader class
- Using Scanner class
- Using Console class
- Using BufferedReader class
we can take input from the console by wrapping System.in into an InputStreamReader and passing it into the BufferedReader.
It provides an efficient reading as the input gets buffered.
public class A{
public static void main(String[] args) throws IOException {
System.out.println("what's your name?");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
}
}
what's your name?
Amy (input context)
Amy
- Using Scanner class
The Java
Scanner class
breaks the input into tokens using a delimiter that is whitespace by default.
It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using a regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
public class A{
public static void main(String[] args){
String str = "what's your name?/My name is Amy";
//Create scanner with the specified String Object
Scanner scanner = new Scanner(str);
System.out.println("Boolean Result: "+scanner.hasNextBoolean());
scanner.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(scanner.hasNext()){
System.out.println(scanner.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +scanner.delimiter());
scanner.close();
}
}
Boolean Result: false
---Tokenizes String---
what's your name?
My name is Amy
Delimiter used: /
- Using Console class
- The Java
Console class
is used to get input from the console.- It provides methods to read texts and passwords.
- If you read the password using the Console class, it will not be displayed to the user.
- The java.io.Console class is attached to the system console internally.
- The Console class is introduced since 1.5. Consider the following example.
public class A{
public static void main(String[] args){
Console c = System.console();
System.out.println("Enter your name: ");
String n = c.readLine();
System.out.println("Welcome "+n);
}
}
Enter your name:
Exception in thread "main" java.lang.NullPointerException
at model.A.main(A.java:15)
Serialization
Interview Questions
10.What is serialization?
- Serialization in Java is a mechanism of writing the state of an object into a byte stream.
- It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies.
- It is mainly used to travel object’s state on the network (which is known as marshaling).
- Serializable interface is used to perform serialization.
- It is helpful when you require to save the state of a program to storage such as the file.
- At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation).
- With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.
For serializing the object,
we call the writeObject()
method of ObjectOutputStream class, and for deserialization
we call the readObject()
method of ObjectInputStream class.
Advantages of Java Serialization
It is mainly used to travel object’s state on the network (that is known as marshalling).