OCJP Practice Papers - Java I/O Fundamentals
OCJP Practice Papers Java I/O Fundamentals include following topics
- Read and write data from the console
- Use BufferedReader, BufferedWriter, File, FileReader, FileWriter, FileInputStream, FileOutputStream, ObjectOutputStream, ObjectInputStream, andPrintWriter in the java.io package
See the complete syllabus for OCJP here
- Fill in the blanks: Writer is______ that related stream classes______ .
A. a concrete class, extend
B. an abstract class, extend
C. an interface, extend
D. an interface, implement
2. Which of the following methods is defined in java.io.File?
A. createDirectory()
B. getLength()
C. listFile()
D. renameTo()
3. Which method in InputStream can be used in place of calling skip(1)?
A. jump()
B. mark()
C. read()
D. reset()
4. Which methods are classes that implement java.io.Serializable required to
implement?
A. deserialize()
B. serial()
C. serialize()
D. None of the above
5. Fill in the blanks: Given a valid Console instance, reader() returns a__________ ,
while writer() returns a __________.
A. PrintReader, PrintWriter
B. PrintReader, Writer
C. Reader, Writer
D. StringReader, Writer
6. Assuming the file path referenced in the following class is accessible and able to be
written, what is the output of the following program?
package alarm;
import java.io.*;
public class Smoke {
public void sendAlert(File fn) {
try(BufferedWriter w = new BufferedWriter(new FileOutputStream(fn))) {
w.write("ALERT!");
w.flush();
w.write('!');
System.out.print("1");
} catch (IOException e) {
System.out.print("2");
} finally {
System.out.print("3");
}
}
public static void main(String[] testSignal) {
new Smoke().sendAlert(new File("alarm.txt"));
}
}
A. 3
B. 13
C. 23
D. The code does not compile.
7. Which class is used to read information about a directory within the file system?
A. java.io.File
B. java.io.Directories
C. java.io.Directory
D. java.io.Path
8. Which of the following is a high-level stream class that can only be used to wrap a
low-level stream?
A. FileOutputStream
B. FileReader
C. ObjectInputStream
D. PrintWriter
9. Assume the file prime6.txt exists and contains the first six prime numbers as bytes: 2,
3, 5, 7, 11, 13. What is the output of the following application?
package numbers;
import java.io.*;
public class PrimeReader {
public static void main(String[] real) throws Exception {
try (InputStream is = new FileInputStream("prime6.txt")) {
is.skip(1);
is.read();
is.skip(1);
is.read();
is.mark(4);
is.skip(1);
is.reset();
System.out.print(is.read());
}
}
}
A. 11
B. 13
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
10. Fill in the blanks: For a given file, the absolute is the path from the __________to
the file, while the relative path is the path from the __________to the file.
A. current directory, current working directory
B. parent directory, temporary directory
C. root directory, current working directory
D. root directory, parent directory
11. Which statement best describes the following two methods?
public void writeSecret1() throws IOException {
final Writer w = new BufferedWriter(
new FileWriter("dont.open"));
w.write("Secret passcode");
w.close();
}p
ublic void writeSecret2() throws IOException {
try(final Writer w = new BufferedWriter(
new FileWriter("dont.open"))) {
w.write("Secret passcode");
}
}
A. Both methods compile and are equivalent to each other.
B. Neither method compiles.
C. Only one of the methods compiles.
D. The methods compile, but one method may lead to a resource leak.
12. What is the result of compiling and executing the following program?
package vacation;
import java.io.*;
import java.util.*;
public class Itinerary {
private ListString activities = new ArrayList();
private static Itinerary getItinerary(String name) {
return null;
}
public static void printItinerary() throws Exception {
Console c = new Console();
final String name = c.readLine("What is your name?");
final Itinerary stuff = getItinerary(name);
stuff.activities.forEach(s - c.printf(s));
}
public static void main(String[] holidays) throws Exception {
printItinerary();
}
}
A. The code does not compile.
B. The code compiles and prints a NullPointerException at runtime.
C. The code compiles but does not print anything at runtime.
D. None of the above
13. Given the following diagram, which two classes can be placed in the blank boxes?
A. BufferedOutputStream and PrintStream
B. BufferedOutputStream and PrintOutputStream
C. ByteArrayOutputStream and Stream
D. FileOutputStream and OutputStream
14. Lets say we want to write an instance of Cereal to disk, having a name value of
CornLoops. What is the value of name after this object has been read using the
ObjectInputStreams readObject() method?
package breakfast;
public class Cereal {
private String name = "CocoaCookies";
private transient int sugar;
public Cereal() {
super();
this.name = "CaptainPebbles";
}
{
name = "SugarPops";
}
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
public int getSugar() { return sugar; }
public void setSugar(int sugar) {
this.sugar = sugar;
}
}
A. CaptainPebbles
B. CornLoops
C. SugarPops
D. None of the above
15. Which statement best describes the difference between a Writer and an OutputStream
class?
A. Only one of them can write text or character data.
B. Only one of them has built-in methods for writing character data.
C. Only one of them has a flush() method to force the data to be written out.
D. One uses a byte array to process character data more efficiently.
16. What is the output of the following application? It is safe to assume the directories
referenced in the class do not exist prior to the execution of the program and that the
file system is available and able to be written.
package job;
import java.io.*;
public class Resume {
public void resetWorkingDirectory() throws Exception {
File f1 = new File("/templates/proofs");
f1.mkdirs();
File f2 = new File("/templates");
f2.mkdir(); // k1
new File(f2,"draft.doc").createNewFile();
f1.delete();
f2.delete(); // k2
}
public static void main(String... leads) {
try {
new Resume().resetWorkingDirectory();
} catch (Exception e) {
new RuntimeException(e);
}
}
}
A. Line k1 does not compile or triggers an exception at runtime.
B. Line k2 does not compile or triggers an exception at runtime.
C. The code compiles and runs without printing an exception.
D. None of the above
17. Given the following class, three of the values ensure it runs properly on various
different systems. Which value does not?
package magic;
import java.io.*;
public class Store {
private final String directory;
public Store(String directory) {
this.directory = directory;
}
public File getDatabaseFolder(String file) {
return new File(directory + __________ + file);
}
}
A. java.io.File.separator
B. new File(new String()).separatorChar
C. System.getProperty("file.separator")
D. System.getProperty("path.separator")
18. How many compilation errors does the following class contain?
package hero;
import java.io.*;
public class Guitar {
public void readMusic(File f) {
try (BufferedReader r = new BufferedReader(FileReader(f))) {
final String music = null;
try {
while((music = r.readLine()) != null)
System.out.println(music);
} catch (IOException e) {}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {}
}}
A. None
B. One
C. Two
D. Three
19. What is the difference between the two Console methods, format() and printf()?
A. One of them takes an optional list of arguments; the other does not.
B. One of them takes String as input; the other takes an Object.
C. There is no difference between the two methods.
D. Trick question! printf() is not defined in Console.
20. Lets say you want to write a lot of text data to a file in an efficient manner. Which two
java.io stream classes are best to use?
A. FileOutputStream and BufferedOutputStream
B. FileOutputWriter and FileBufferedWriter
C. FileWriter and BufferedWriter
D. ObjectOutputStream and BufferedWriter
21. Assume the file referenced in the StudentManager class exists and contains data.
Which statement about the following class is correct?
package school;
import java.io.*;
class Student implements Serializable {}
public class StudentManager {
public static void main(String[] grades) {
try(ObjectInputStream ios = new ObjectInputStream(
new FileInputStream(new File("C://students.data")))) {
Student record;
while((record = (Student)ios.readObject()) != null) {
System.out.print(record);
}
} catch (EOFException e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
A. The code does not compile.
B. The code compiles but prints an exception at runtime.
C. The program runs and prints all students in the file.
D. The program runs but may only print some students in the files.
22. Which java.io class does not have a complementary input stream?
A. BufferedOutputStream
B. BufferedWriter
C. FileWriter
D. PrintWriter
23. Assuming the path /Earth does not exist within the file system, what is the output of
the following program?
package center;
import java.io.*;
public class Journey {
public static void main(String[] dig) {
File file = new File("/Earth");
System.out.print(file.getParent()
+" - "
+file.getParent().getParent()); } }
A. / - /
B. / - null
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
24. Which statements about executing the following program are true?
package test;
import java.io.*;
public class Turing {
public static void main(String... robots) {
Console c = System.console();
final String response = c.readLine("Are you human?");
System.err.print(response);
}
}
I. The program may ask the user a question and print the response to the error
stream.
II. The program may throw a NullPointerException at runtime.
III. The program may wait indefinitely.
A. I
B. I and III
C. II and III
D. I, II, and III
25. Which of the following statements about the deleteTree() method is correct?
public void deleteTree(File f) {
if(!f.isDirectory())
f.delete();
else {
Stream.of(f.list())
.forEach(s - deleteTree(s));
f.deleteDirectory();
}
}
A. It compiles and is capable of deleting a directory tree.
B. If one line were modified, it would be capable of deleting a directory tree.
C. If two lines were modified, it would be capable of deleting a directory tree.
D. None of the above
26. Which of the following is not a built-in stream in Java?
A. System.err
B. System.in
C. System.info
D. System.out
27. Assuming the file path referenced in the following class is accessible and able to be
written, what is the output of the following program?
package store;
import java.io.*;
public class Furniture {
public final static void main(String... inventory) throws Exception {
Writer w = new FileWriter("couch.txt");
try (BufferedWriter bw = new BufferedWriter(w)) {
bw.write("Blue coach on Sale!");
} finally {
w.flush();
w.close();
}
System.out.print("Done!");
}
}
A. Done!
B. The code does not compile for one reason.
C. The code does not compile for two reasons.
D. The code compiles but throws an exception at runtime.
28. Given an instance of Console c, which of the following method calls is not a way to
read input from the user?
A. c.reader().read()
B. c.reader().readLine()
C. c.readLine()
D. c.readPassword()
29. The copyPidgin() method is used to copy the contents of one file to another. Which
statement about the implementation is correct?
package birds;
import java.io.*;
public class Pidgin {
public void copyPidgin(File s, File t) throws Exception {
try(InputStream is = new FileInputStream(s);
OutputStream os = new FileOutputStream(t)) {
byte[] data = new byte[123];
int chirps;
while((chirps = is.read(data))0) {
os.write(data);
}}
}}
A. The class does not compile because read(byte[]) and write(byte[]) can only be
called on BufferedInputStream and BufferOutputStream, respectively.
B. The method correctly copies the contents of all files.
C. The method correctly copies the contents of some files.
D. The method will always throw an exception at runtime because the data array size
is not a power of 2.
30. Using what you know about java.io stream class names, what would a nonexistent
class named BufferedFileReader most likely be used for?
A. Reading a small text file from a remote network
B. Reading an image from disk
C. Reading large text files from a file system
D. Reading serialized data from disk
31. What is the output of the following application?
package factory;
import java.io.*;
public class WidgetProcessor {
public int getWidgetNumber(byte[] data) throws Exception {
try (InputStream is = new ByteArrayInputStream(data)) {
is.read(new byte[2]);
if(!is.markSupported()) return -1;
is.mark(5);
is.read();is.read();
is.skip(3);
is.reset();
return is.read();
}
}
public static void main(String... sprockets) throws Exception {
final WidgetProcessor p = new WidgetProcessor();
System.out.print(p.getWidgetNumber(new byte[] {1,2,3,4,5,6,7}));
}
}
A. 3
B. 5
C. 7
D. An exception is thrown at runtime.
32. Assuming the working directory is accessible, empty, and able to be written, how many
file system objects does the following class create?
1: package kitchen;
2: import java.io.*;
3: public class Bakers {
4: public static void main(String... tooMany) throws IOException {
5: File cake = new File("cake.txt");
6: Writer pie = new FileWriter("pie.txt");
7: pie.flush();
8: new File("fudge.txt").mkdirs();
9: } }
A. None
B. One
C. Two
D. Three
33. Lets say you wanted to read data from a file stored on disk that consists of String,
long, and Object values? Given that the file is quite large, you intend to use three
classes to achieve this result. Which of the following is not one of the three classes
you should use?
A. BufferedInputStream
B. BufferedReader
C. FileInputStream
D. ObjectInputStream
34. Which statement best describes the following two methods?
public String getNameQuick() throws IOException {
final BufferedReader r = new BufferedReader(
new FileReader("saved.name"));
final String name = r.readLine();
r.flush();
return name;
}p
ublic String getNameSafely() throws IOException {
try(final BufferedReader r = new BufferedReader(
new FileReader("saved.name"))) {
final String name = r.readLine();
r.flush();
return name;
}}
A. Both methods compile and are equivalent to each other.
B. Neither method compiles.
C. Only one of the methods compiles.
D. The methods compile, but one method may lead to a resource leak.
35. What is the output of the following application? Assume the System.console() is
available and the user enters badxbad and presses Enter.
package hardway;
import java.io.*;
public class InconvenientImplementation {
public static void main(String... dontDoThis) throws Exception {
Console c = System.console();
if(c != null) {
c.writer().write('P');
c.writer().write('a');
c.writer().write('s');
c.writer().write('s');
c.writer().flush(); // t1
int i;
StringBuilder sb = new StringBuilder();
while((i = c.reader().read()) != 'x') { // t2
sb.append((char)i);
}
c.writer().format("Result: %s",sb.toString());
}
}
}
A. Result: bad
B. Line t1 does not compile or triggers an exception at runtime.
C. Line t2 does not compile or triggers an exception at runtime.
D. None of the above
36. Why does Console readPassword() return a char array rather than a String?
A. It improves performance.
B. It improves security.
C. Passwords must be stored as a char array.
D. String cannot hold the individual password characters.
37. Which statement about the following program is true?
package mystical;
import java.io.*;
public class Unicorn {
public void findUnicorns() {
try(InputStream o = new ObjectInputStream(readBook())) {
while(o.read() != -1) {
System.out.println(o.read());
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private InputStream readBook() throws IOException {
return new BufferedInputStream(new FileReader("magic.book"));
}
public static void main(String... horn) {
new Unicorn().findUnicorns();
}
}
A. The code does not compile.
B. The program prints every byte in the file without throwing an exception.
C. The program prints every other byte in the file without throwing an exception.
D. The program throws an EOFException when the end of the file is reached.
38. Choose the class that is least likely to be marked Serializable.
A. A class that holds data about the amount of rain that has fallen in a given year
B. A class that manages the memory of running processes in an application
C. A class that stores information about apples in an orchard
D. A class that tracks the amount of candy in a gumball machine
39. What is the output of the following application?
package cell;
import java.io.*;
public class TextMessage {
public String receiveText() throws Exception {
try (Reader r = new FileReader("messages.txt")) {
StringBuilder s = new StringBuilder();
int c;
while((c = r.read()) != -1) {
s.append((char)c);
if(r.markSupported()) {
r.mark(100);
r.skip(10);
r.reset();
}
}
return s.toString();
}
}
public void sendText(String message) throws Exception {
try (Writer w = new FileWriter("messages.txt")) {
for(int i=0; imessage.length(); i++) {
w.write(message.charAt(i));
w.skip(1);
}
}
}
public static void main(String[] minutes) throws Exception {
final TextMessage m = new TextMessage();
m.sendText("You up?");
System.out.println(m.receiveText());
} }
A. You up?
B. Y o u u p ?
C. The code does not compile because of the receiveText() method.
D. The code does not compile because of the sendText() method.
40. What is the output of the following program? Assume the file paths referenced in the
class exist and are able to be written to and read from.
package heart;
import java.io.*;
public class Valve implements Serializable {
private int chambers = -1;
private transient Double size = null;
private static String color;
public Valve() {
this.chambers = 3;
color = "BLUE";
}
public static void main(String[] love) throws Throwable {
try (ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("scan.txt"))) {
final Valve v = new Valve();
v.chambers = 2;
v.size = 10.0;
v.color = "RED";
o.writeObject(v);
}
new Valve();
try (ObjectInputStream o = new ObjectInputStream(
new FileInputStream("scan.txt"))) {
Valve v = (Valve)o.readObject();
System.out.print(v.chambers+","+v.size+","+v.color);
}
}
{ chambers = 4; }
}
A. 2,null,RED
B. 2,null,BLUE
C. 3,10.0,RED
D. The code does not compile.
OCJP Practice Test, Certification Path, Tips/Tricks
- Oracle (OCJP) Java Certification Exam
- Java Certification Tips And Tricks
- OCJP Practice Papers - Java Basics
- OCJP Practice Papers - Operators And Decision Constructs
- OCJP Practice Papers-A Advanced Java Class Design
- OCJP Practice Papers Creating And Using Arrays
- OCJP Practice Papers Using Loop Constructs
- OCJP Practice Papers - Generics And Collections
- OCJP Practice Papers - Lambda Built-In Functional Interfaces
- OCJP Practice Papers Java Class Design
- OCJP Practice Papers - Java Stream API
- OCJP Practice Papers - Exceptions And Assertions
- OCJP Practice Papers - Date/Time API
- OCJP Practice Papers - Java I/O Fundamentals
- OCJP Practice Papers - Working With Methods And Encapsulation
- OCJP Practice Papers - Working With Inheritance
- OCJP Practice Papers - Handling Exceptions
- OCJP Practice Papers - Selected Classes From Java API
- OCJP Practice Papers - Java File I/O Nio.2
- OCJP Practice Papers - Java Concurrency