Java - IO - Interview Questions and Answers on FileOutputStream

Q1.  Which exceptions should be handled with the following code ?

FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));

Ans. FileNotFoundException

Q2.  Will this code compile fine ?

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));

Ans. Yes.

Q3.  What is the problem with this code ?

class BuggyBread1 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
   objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to implement Serializable.

This will throw java.io.NotSerializableException upon execution.

Q4.  Will this code run fine if BuggyBread2 doesn't implement Serializable interface ?

class BuggyBread1 implements Serializable{

private BuggyBread2 buggybread2 = new BuggyBread2();

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
   objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Ans. No, It will throw java.io.NotSerializableException.

Q5.  Will this code work fine if BuggyBread2 doesn't implement Serializable ?

class BuggyBread1 extends BuggyBread2 implements Serializable{

private int x = 5;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
   objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Ans. Yes.

Q6. Which interfaces are implemented by FileOutputStream?

Ans.[, Closeable, AutoCloseable, Flushable]

Q7. What is the package name for FileOutputStream class?

Ans. java.io