Java 8 Streams

Ace your homework & exams now with Quizwiz!

List seven methods of PrintWriter

*F-P-P-P-W-F-C* format() printf() println() print() write() flush() close()

List six methods of Files class located in java.nio.file.Files

*M-C-N-E-D-D* - ALL *Static methods* path *move*(Path scr, Path des, CopyOption... options) path *copy*(Path scr, Path des, CopyOption... options) boolean *notExists*( Path path, LinkOption... options) boolean *exists*( Path path, LinkOption... options) void *delete*(Path path) boolean *deleteIfExists*( Path path)

List 8 methods in File class

*M-E-D-I-I-C-L-R* mkdir() exists() delete() isDirectory() isFile() createNewFile() list() renameTo()

List 4 methods of BufferedWriter

*N-W-F-C* newLine() write() flush() close()

List 3 methods of FileWriter

*W-F-C* write() flush() close()

What method am I? Closes the stream and releases any system resources associated with it.

*close()* located in: FileWriter BufferedWriter PrintWriter

FileWriter BufferedWriter PrintWriter All contain two common methods. Named them.

*flush()* and *close()*. *flush()*: guarantees that the last of the data gets written to disk. *close()*: Closes the stream and releases any system resources associated with it.

What method am I? guarantees that the last of the data gets written to disk.

*flush()* located in: FileWriter BufferedWriter PrintWriter

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello World"); s1.insert(6 , "Good "); System.out.println(s1); } } a) HelloGoodWorld b) HellGoodoWorld c) HellGood oWorld d) Hello Good World

d

What is the output of this program? class output { public static void main(String args[]) { StringBuffer c = new StringBuffer("Hello"); StringBuffer c1 = new StringBuffer(" World"); c.append(c1); System.out.println(c); } } a) Hello b) World c) Helloworld d) Hello World

d

What is the output of this program? import java.io.*; class Chararrayinput { public static void main(String[] args) { String obj = "abcdefgh"; int length = obj.length(); char c[] = new char[length]; obj.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 1, 4); int i; int j; try { while((i = input1.read()) == (j = input2.read())) { System.out.print((char)i); } } catch (IOException e) { e.printStackTrace(); } } } a) abc b) abcd c) abcde d) None of the mentioned

d

What is the output of this program? import java.io.*; public class filesinputoutput { public static void main(String[] args) { String obj = "abc"; byte b[] = obj.getBytes(); ByteArrayInputStream obj1 = new ByteArrayInputStream(b); for (int i = 0; i < 2; ++ i) { int c; while((c = obj1.read()) != -1) { if(i == 0) { System.out.print(Character.toUpperCase((char)c)); obj2.write(1); } } System.out.print(obj2); } } } a) AaBaCa b) ABCaaa c) AaaBaaCaa d) AaBaaCaaa

d

OutputStream object's helper methods

- can be used to write to stream or to do other operations on the stream. - public void close() throws IOException{} -protected void finalize()throws IOException {} -public void write(int w)throws IOException{} -public void write(byte[] w)

java.io package

- contains nearly every class you might ever need to perform input and output (I/O) in Java - All these streams represent an input source and an output destination - The stream in the java.io package supports many data such as primitives, object, localized characters, etc.

what is optional

- either a wrapper for an object or no object - intended to be null safe

FileInputStream

- is used for reading data from the files. - Objects can be created using the keyword new and there are several types of constructors available. InputStream f = new FileInputStream("C:/java/hello"); or File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f);

FileOutputStream

- is used to create a file and write data into it. - The stream would create a file, if it doesn't already exist, before opening it for output. ex1: OutputStream f = new FileOutputStream("C:/java/hello") ex2: File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);

define stateful vs stateless operation

-incorporate state from previously processed elements when processing the current element -cannot be processed individually, they need to be compared with one another thus requiring information to be retained -can be processed without the need for sharing information between them for processing -retain no state during the execution of the pipeline.

Flush in Buffer Steams

1. Flush is valid for only Output streams. 2. Some buffered output classes support autoflush, specified by an optional constructor argument 3. When auto-flush is enabled certain key events cause the buffer to be flushed. e.g autoflush Printwriter object flushes the buffer on every invocation of println or format.

Which of the following exceptions will be thrown by the reset() method if the markSupported() method returns false? A IOException B UnsupportedEncodingException C InterruptedException D SocketException

A IOException

Which subclass of OutputStream is used to write data onto a network connection? A TelnetOutputStream B FileOutputStream C ByteArrayOutputStream D NetworkOutputStream

A TelnetOutputStream

LineNumberReader

A buffered character-input stream that keeps track of line numbers.

StringWriter

A character stream that collects its output in a string buffer, which can then be used to construct a string.

Which of the following methods forcefully breaks the deadlock to send the buffered stream data even if the buffer isn't yet filled? A flush() B read() C close() D write()

A flush()

PipedInputStream

A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.

Which of the following is a valid PrintStream method? A public void println() B public void print() C public void printerln() D public void printer()

A public void println()

What is a method of the Writer class? A public void write(int c) throws IOException B public void writen(char[] text) throws IOException C public void writer(String s) throws IOException D public void writer(String s, int offset, int length) throws IOException

A public void write(int c) throws IOException

List the six main I/O classes in Java 7 API

Abbreviation: *F-F-F-B-B-P* File FileWriter FileReader BufferedReader BufferedWriter PrintWriter

Reader

Abstract class for reading character streams.

FilterReader

Abstract class for reading filtered character streams.

FilterWriter

Abstract class for writing filtered character streams.

Writer

Abstract class for writing to character streams.

ObjectOutputStream

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.

OutputStreamWriter

An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.

What class am I? Low-level FileWriter more efficient

BufferedWriter class

BufferedWriter makes low - level _____ more _____

BufferedWriter makes low - level *FileWriter* more *EFFICIENT*

15.7.2 Q2: Which of the following statements is false? a. A LineNumberReader is a buffered character stream that tracks the number of lines read. b. Classes FileReader and FileWriter perform character-based file I/O. c. Class PipedReader and class PipedWriter implement piped-character streams for transferring data between threads. d. Class StringReader and StringWriter read characters from and write characters to Streams, respectively.

Class StringReader and StringWriter read characters from and write characters to Streams, respectively. Actually, class StringReader and StringWriter read characters from and write characters to Strings, respectively.

collectors - string

Collectors.joining() Collectors.joining(CharSequence delimiter) Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

collectors - optional

Collectors.maxBy(Predicate<T> test) Collectors.minBy(Predicate<T> test) Collectors.reducing(BinaryOperator<T> op)

collectors - partitioningBy

Collectors.partitioningBy(Predicate<T> classifier) Collectors.partitioningBy(Predicate<T> classifier, Collector downstreamCollector) e.g. Map<Boolean, List<Locale>> englishAndOtherLocales = locales.collect(Collectors.partitioningBy(l -> l.getLanguage().equals("en"))); List<Locale>> englishLocales = englishAndOtherLocales.get(true);

collectors - reducing overloaded

Collectors.reducing(T seed, BinaryOperator<T> op) Collectors.reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)

Console is useful to write _____ engines for _____ _____

Console is useful to write *TEST* engines for *UNIT TESTING*

Console makes it easy to accept input from _____ _____

Console makes it easy to accept input from *COMMAND LINE*

C.R.U.D

Create Retrieve Update Delete

Which of the following is not a valid method of the DataOutputStream? A public final void writeInt(int i) throws IOException B public final void writeLong(long l) throws IOException C public final void writeFloat(float f) throws IOException D public final void writeChar(String s) throws IOException

D public final void writeChar(String s) throws IOException

In File class close() method guarantees the last data gets written to disk. True or false

False. *close() frees* up expensive operating *system resources*

What class do you need to use to work with Files?

File Class ---> import java.io.FILE

What class am I? I make a new empty file but not the data. I search for files and delete files

File class

File class makes a new _____file but not the _____ .

File class makes a new *EMPTY* file but not the *DATA*. It contains a number of other functions in methods: *exists()*- Tests whether the file or directory denoted by this abstract pathname exists. *isFile()* - Tests whether the file denoted by this abstract pathname is a normal file. *isDirectory()* - Tests whether the file denoted by this abstract pathname is a directory. *mkdirs()* - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. *mkdir()* - Creates the directory named by this abstract pathname. etc.

FileWriter class _____ characters (single or _____ ) in a stream of _____ to a file.

FileWriter class *WRITES* characters (single or *WHOLE*) in a stream of *CHARS* to a file.

FileWriter writes single _________ at a time to file

FileWriter writes single *chars* at a time to file

binary files

Files created using byte-based streams - are read by programs that understand the specific content of the file and the ordering of that content.

text files

Files created using character-based streams - can be read by text editors

JDK 1.0's I/O capabilities are suitable for streaming bytes, but cannot properly stream characters because they don't account for character encodings. JDK 1.1 overcame this problem by introducing writer/reader classes that take character encodings into account. For example, the java.io package includes FileWriter and FileReader classes for writing and reading character streams.

How are character encodings handled in classic I/O?

File content can be accessed sequentially or randomly.

How can file content be accessed?

using parsing methods

How can you convert a numeric string such as "123.23" into its binary equivalent?

The java.io package's classes default to resolving relative paths against the current user (also known as working) directory, which is identified by the system property user.dir and which is typically the directory in which the JVM was launched. (You obtain a system property value by calling the java.lang.System class's getProperty() method.)

How do you obtain the current user (also known as working) directory?

JDK 1.4 supports readiness selection by providing selectors, which are instances of the java.nio.channels.Selector class that can examine one or more channels and determine which channels are ready for reading or writing. This way a single thread can manage multiple channels (and, therefore, multiple network connections) efficiently. Being able to use fewer threads is advantageous where thread creation and thread context switching is expensive in terms of performance and/or memory use.

How does JDK support "readiness selection"?

JDK 1.4 supports regular expressions via the java.util.regex package and its Pattern and Matcher classes.

How does JDK support regular expressions?

Java provides the java.nio.channels.ScatteringByteChannel interface to support scattering and the java.nio.channels.GatheringByteChannel interface to support gathering. ScatteringByteChannel offers the following methods: long read(ByteBuffer[] buffers, int offset, int length) long read(ByteBuffer[] buffers) GatheringByteChannel offers the following methods: long write(ByteBuffer[] buffers, int offset, int length) long write(ByteBuffer[] buffers)

How does Java support Scatter/Gather I/O?

Java supports channels via its java.nio.channels and java.nio.channels.spi packages. Applications interact with the types located in the former package; developers who are defining new selector providers work with the latter package.

How does Java support channels?

Files can be created and/or opened for random access in which a mixture of write and read operations at various locations can occur until the file is closed. Java supports this random access by providing a java.io.RandomAccessFile class.

How does Java support random access?

I/O is classified as block-oriented or stream-oriented. Reading from or writing to a file is an example of block-oriented I/O. In contrast, reading from the keyboard or writing to a network connection is an example of stream-oriented I/O.

How is I/O classified?

1. RandomAccessFile(File file, String mode): Create and open a new file when it doesn't exist or open an existing file. The file is identified by file's abstract path and is created and/or opened according to mode. 2. RandomAccessFile(String path, String mode): Create and open a new file when it doesn't exist or open an existing file. The file is identified by path and is created and/or opened according to mode.

How many constructors were declared in RandomAccessFile class?

Buffers possess four properties: - Capacity: The total number of data items that can be stored in the buffer. The capacity is specified when the buffer is created and cannot be changed later. - Limit: The zero-based index of the first element that should not be read or written. In other words, it identifies the number of "live" data items in the buffer. - Position: The zero-based index of the next data item that can be read or the location where the data item can be written. - Mark: A zero-based index to which the buffer's position will be reset when the buffer's reset() method (presented shortly) is called. The mark is initially undefined. These four properties are related as follows: 0 <= mark <= position <= limit <= capacity

How many properties does a buffer posses?

When you are done with a stream, you will often want to look at its elements. You can call the iterator method, which yields an old-fashioned iterator that you can use to visit the elements. Alternatively, you can call the forEach method to apply a function to each element: stream.forEach(System.out::println); On a parallel stream, the forEach method traverses elements in arbitrary order. If you want to process them in stream order, call forEachOrdered instead.

How to collect results from a stream?

For collecting stream elements to another target, there is a convenient collect method that takes an instance of the Collector interface. The Collectors class provides a large number of factory methods for common collectors. To collect a stream into a list or set, simply call List<String> result = stream.collect(Collectors.toList()); Set<String> result = stream.collect(Collectors.toSet()); TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));

How to collect stream result to collection?

Use Collectors.toMap: Map<Integer, String> idToName = people.collect( Collectors.toMap(Person::getId, Person::getName));

How to collect stream results to a map?

String[] result = stream.toArray(String[]::new);

How to collect stream results to an array?

To create a File instance, call a constructor such as File(String path), which creates a File instance that stores the path string: File file1 = new File("/x/y");

How to create a File instance?

ByteBuffer and the other primitive-type buffer classes declare various class methods for creating a buffer of that type. For example, ByteBuffer declares the following class methods for creating ByteBuffer instances: - ByteBuffer allocate(int capacity) - ByteBuffer allocateDirect(int capacity) - ByteBuffer wrap(byte[] array) - ByteBuffer wrap(byte[] array, int offset, int length) ByteBuffer buffer = ByteBuffer.allocate(10); byte[] bytes = new byte[200]; ByteBuffer buffer2 = ByteBuffer.wrap(bytes);

How to create a buffer?

If you want to write a method that creates an Optional object, there are several static methods for that purpose, including Optional.of(result) and Optional.empty(). public static Optional<Double> inverse(Double x) { return x == 0 ? Optional.empty() : Optional.of(1 / x); }

How to create optional values?

IntStream stream = IntStream.of(1, 1, 2, 3, 5); stream = Arrays.stream(values, from, to); // values is an int[] array IntStream zeroToNinetyNine = IntStream.range(0, 100); // Upper bound is excluded IntStream zeroToHundred = IntStream.rangeClosed(0, 100); // Upper bound is included

How to create primitive type streams?

Read-only view buffers can be created by calling a method such as ByteBuffer asReadOnlyBuffer(). Any attempt to change a read-only view buffer's content results in ReadOnlyBufferException. However, the original buffer content (provided that it isn't read-only) can be changed, and the read-only view buffer will reflect these changes.

How to create read-only view buffer?

Using stream() or parallelStream() methods

How to create stream from Collection interface?

Using the static Stream.of() method. Stream<String> words = Stream.of(contents.split("\\PL+")); Stream<String> song = Stream.of("gently", "down", "the", "stream"); Use Arrays.stream(array, from, to) to make a stream from array elements between positions from (inclusive) and to (exclusive). To make a stream with no elements, use the static Stream.empty method

How to create stream from an array?

The JDK provides a serialver tool for calculating the SUID. For example, to generate an SUID for Employee class, change to the directory containing Employee.class and execute the following command: $ serialver Employee

How to generate SUID?

Normally, the serialization mechanism writes out a class's instance fields to the underlying output stream. However, you can prevent this from happening by declaring a private void writeObject(ObjectOutputStream oos) method in that class. When the serialization mechanism discovers this method, it calls the method instead of automatically outputting instance field values. The only values that are output are those explicitly output via the method. Conversely, the deserialization mechanism assigns values to a class's instance fields that it reads from the underlying input stream. However, you can prevent this from happening by declaring a private void readObject(ObjectInputStream ois) method. When the deserialization mechanism discovers this method, it calls the method instead of automatically assigning values to instance fields. The only values that are assigned to instance fields are those explicitly assigned via the method.

How to implement custom serialization and deserialization in Java?

You can mark a buffer by invoking the mark() method and later return to the marked position by invoking reset().

How to mark a buffer?

There are two ways to obtain a channel: - The java.nio.channels package provides a Channels utility class that offers two methods for obtaining channels from streams. For each of the following methods, the underlying stream is closed when the channel is closed, and the channel isn't buffered: 1. WritableByteChannel newChannel(OutputStream outputStream) returns a writable byte channel for the given outputStream. 2. ReadableByteChannel newChannel(InputStream inputStream) returns a readable byte channel for the given inputStream. - Various classic I/O classes have been retrofitted to support channel creation. For example, java.io.RandomAccessFile declares a FileChannel getChannel() method for returning a file channel, and java.net.Socket declares a SocketChannel getChannel() method for returning a socket channel.

How to obtain a channel?

Use one of the summarizing(Int|Long|Double) methods: IntSummaryStatistics summary = stream.collect( Collectors.summarizingInt(String::length)); double averageWordLength = summary.getAverage(); double maxWordLength = summary.getMax();

How to reduce the stream results to a sum, average, maximum, or minimum?

For sorting a stream, there are several variations of the sorted method. One works for streams of Comparable elements, and another accepts a Comparator. Stream<String> longestFirst = words.stream().sorted(Comparator.comparing(String::length).reversed());

How to sort a stream?

Your first task is to have the class of the object that's to be serialized implement the java.io.Serializable interface, either directly or indirectly via the class's superclass. The rationale for implementing Serializable is to avoid unlimited serialization. Your second task is to work with the ObjectOutputStream class and its writeObject() method to serialize an object and the OutputInputStream class and its readObject() method to deserialize the object. ObjectOutputStream oos = null; ObjectInputStream ois = null; try { FileOutputStream fos = new FileOutputStream(FILENAME); oos = new ObjectOutputStream(fos); Employee emp = new Employee("John Doe", 36); oos.writeObject(emp); oos.close(); oos = null; FileInputStream fis = new FileInputStream(FILENAME); ois = new ObjectInputStream(fis); emp = (Employee) ois.readObject(); // (Employee) cast is necessary. ois.close(); System.out.println(emp.getName()); System.out.println(emp.getAge()); } catch (ClassNotFoundException cnfe) { System.err.println(cnfe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } finally { if (oos != null) try { oos.close(); } catch (IOException ioe) { assert false; // shouldn't happen in this context } if (ois != null) try { ois.close(); } catch (IOException ioe) { assert false; // shouldn't happen in this context } }

How to use default serialization and deserialization?

The key to using Optional effectively is to use a method that either produces an alternative if the value is not present, or consumes the value only if it is present. String result = optionalString.orElse(""); String result = optionalString.orElseGet(() -> Locale.getDefault().getDisplayName()); String result = optionalString.orElseThrow(IllegalStateException::new); optionalValue.ifPresent(v -> results.add(v)); or optionalValue.ifPresent(results::add);

How to use optionals?

ByteBuffer and the other primitive-type buffer classes declare several overloaded put() and get() methods for writing data items to and reading data items from a buffer. These methods are absolute when they require an index argument or relative when they don't require an index. ByteBuffer buffer = ByteBuffer.allocate(7); buffer.put((byte) 10).put((byte) 20).put((byte) 30); for (int i = 0; i < buffer.position(); i++) System.out.println(buffer.get(i));

How to write to and read from a buffer?

The InputStream class also has three less commonly used methods that allow programs to back up and reread data they've already read. These are:

In order to reread data, mark the current position in the stream with the mark() method. At a later point, you can reset the stream to the marked position using the reset() method *In practice, more streams don't support marking and resetting than do (check via "markSupported()")

throw IOException

Industrial strength file, and directory, processing programs require extensive exception handling to recover from such possibilities

What kind of stream would you use to read data into a program?

Input stream

InputStreamReader and OutputStreamWriter mechanism

InputStreamReader contains an underlying input stream from which it reads raw bytes. It translates these bytes into Unicode characters according to a specified encoding. An OutputStreamWriter receives Unicode characters from a running program. It then translates those characters into bytes using a specified encoding and writes the bytes onto an underlying output stream

FilenameFilter

Instances of classes that implement this interface are used to filter filenames.

FileDescriptor

Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes.

RandomAccessFile

Instances of this class support both reading and writing to a random access file.

Primitive Supplier classes and method

IntSupplier - getAsInt() LongSupplier - getAsLong() DoubleSupplier - getAsDouble()

how to create Primitive Stream

Int|Long|DoubleStream.empty() Int|Long|DoubleStream.generate(Int|Long|DoubleSupplier supplier) Int|Long|DoubleStream.iterate(int|long|double seed, Int|Long|DoubleUnaryOperator f) Int|Long|DoubleStream.of(int|long|double... x) Int|LongStream.range(n, n) Int|LongStream.rangeClosed(n, n) concat(XYZStream a, XYZStream b)

EOFException

Method readObject throws if an attempt is made to read beyond the end of the file

ClassNotFoundException

Method readObject throws if the class for the object being read cannot be located

What does the File class contain?

Methods for obtaining file and directory properties ->length of a file ->path of a file ->check if file exists

Console

Methods to access the character-based console device, if any, associated with the current Java virtual machine.

Chaining a BufferedReader to the InputStreamReader example

Methods: public BufferedReader(Reader in, int bufferSize) public BufferedReader(Reader in)public BufferedWriter(Writer out)public BufferedWriter(Writer out, int bufferSize)

ObjectInput

ObjectInput extends the DataInput interface to include the reading of objects.

readObject

ObjectInput interface method reads and returns a reference to an Object from an InputStream.

ObjectOutput

ObjectOutput extends the DataOutput interface to include writing of objects.

writeObject

ObjectOutput interface method takes an Object as an argument and writes its information to an OutputStream.

DirectoryStream interface

Objects of classes that implement this interface enable a program to iterate through the contents of a directory.

Path interface

Objects of classes that implement this interface represent the location of a file or directory. Path objects do not open files or provide any file-processing capabilities.

Which of these class contains the methods print() & println()? a) System b) System.out c) BUfferedOutputStream d) PrintStream

d

Which of these class is used to read from byte array? a) InputStream. b) BufferedInputStream. c) ArrayInputStream. d) ByteArrayInputStream.

d

Which of these is used to read a string from the input stream? a) get() b) getLine() c) read() d) readLine()

d

Which of these methods can be used to writing console output? a) print() b) println() c) write() d) All of the mentioned

d

15.3 Q7: Which of the following statements is false? a. Path method isAbsolute returns a boolean indicating whether a Path represents an absolute path to a file or directory. b. Files static method getLastModifiedTime receives a Path and returns a FileTime (package java.nio.file.attribute) indicating when the file was last modified. c. Files static method size receives a Path and returns a long representing the number of bytes in the file or directory. For directories, the value returned is platform specific. d. All of the above are true.

d All of the above are true.

Path is an: a) abstract class b) static class c) class d) interface

d is correct

Externalizable

Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Pipe lining

Operations can be viewed as a database-like query on the data source.

3 ways to create Optional<T>

Optional.of(T t) Optional.empty() Optional.ofNullable(T t)

optional reduction operations

Optional<T> max(Comparator<? super T> comparator) Optional<T> min(Comparator<? super T> comparator) Optional<T> findAny() Optional<T> findFirst() Optional<T> reduce(BinaryOperator<T> accumulator) e.g. values.reduce((x,y) -> x+y)

What kind of stream would you use to write data from a program?

Output stream

We can write data to a file by using a/an ______

OutputStream

Look at the following header void displayPoint(Point<Number> myPoint) Which of the following objects would we be allowed to pass as an argument to the displayPoint method?

Point<Number> p;

What class am I? Prints formatted representations of objects to a text-output stream.

PrintWriter class

PrintWriter class prints _____ representations of _____ to a text output stream

PrintWriter class prints *FORMATTED* representations of *OBJECTS* to a text output stream

A.java and Log.txt below are located in folder: C:\a What is the output when code run? import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 =Paths.get("Log.txt"); System.out.println( p1.isAbsolute()); }}

Prints false As Paths.get("*Log.txt*"); is *not* an *absolute path* it is a *relative* path. The following would return true: Path p1 = Paths.get("*C:\\a\\Log.txt*"); indicating an *absolute path* to Log.txt

ObjectInputStream.GetField

Provide access to the persistent fields read from the input stream.

ObjectOutputStream.PutField

Provide programmatic access to the persistent fields to be written to ObjectOutput.

Paths class

Provides static methods used to get a Path object representing a file or directory location.

BufferedReader

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Draw an Input stream diagram

SOURCE ---> INPUT STREAM ---> PROGRAM In the input stream there is data that is waiting to be consumed by something, in this case, the program

Standard Streams

STDIN, STDOUT and STDERR.

ObjectStreamClass

Serialization's descriptor for classes.

A/An ______ is used to accept connections from remote Sockets

ServerSocket

Data processing operations

Stream operations can be executed either sequentially or in parallel

2 ways to create infinite streams

Stream.generate(Supplier<T> s) Stream.iterate(T seed, UnaryOperator<T> f) e.g. Stream<String> s1 = Stream.generate(()->"echo"); Stream<String> s2 = Stream.generate(Math::random); Stream<BigInteger> s3 = Stream.iterate(BigInteger.ZERO, n -> n .add(BigInteger.ONE)); p.s. using infinite streams can cause hang

3 ways to create finite streams

Stream.of(T t) Stream.of(T... t) Stream.empty()

Source

Streams consume from a data-providing source such as collections, arrays, or I/O resources.

What is the most important concept about FILE IO?

Streams, the core concept in Java IO.

InputStream

This abstract class is the superclass of all classes representing an input stream of bytes.

OutputStream

This abstract class is the superclass of all classes representing an output stream of bytes.

StringBufferInputStream Deprecated

This class does not properly convert characters into bytes.

CharArrayReader

This class implements a character buffer that can be used as a character-input stream.

CharArrayWriter

This class implements a character buffer that can be used as an Writer.

SerializablePermission

This class is for Serializable permissions.

FilterOutputStream

This class is the superclass of all classes that filter output streams.

What are some properties of the FileOutputStream?

This class makes it possible to write to a file as a stream of bytes

Standard Streams : Standard Output

This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out.

Standard Streams : Standard Error

This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err.

T/F: In Java all output streams have the same basic methods to write data and all input streams use the same basic methods to read data

True

File offers additional constructors for instantiating this class. For example, the following constructors merge parent and child paths into combined paths that are stored in File objects: - File(String parent, String child) creates a new File instance from a parent path string and a child path string. - File(File parent, String child) creates a new File instance from a parent path File instance and a child path string. File file3 = new File("prj/books/", "io");

What are additional constructors for File class?

Buffers are the foundation for NIO operations. Essentially, NIO is all about moving data into and out of buffers. A process such as the JVM performs I/O by asking the operating system to drain a buffer's contents to storage via a write operation. Similarly, it asks the operating system to fill a buffer with data read from a storage device.

What are buffers?

- "r" informs the constructor to open an existing file for reading only. Any attempt to write to the file results in a thrown instance of the java.io.IOException class. - "rw" informs the constructor to create and open a new file when it doesn't exist for reading and writing or open an existing file for reading and writing. - "rwd" informs the constructor to create and open a new file when it doesn't exist for reading and writing or open an existing file for reading and writing. Furthermore, each update to the file's content must be written synchronously to the underlying storage device. - "rws" informs the constructor to create and open a new file when it doesn't exist for reading and writing or open an existing file for reading and writing. Furthermore, each update to the file's content or metadata must be written synchronously to the underlying storage device.

What are constructor's mode argument for RandomAccessFile?

1. A stream does not store its elements. They may be stored in an underlying collection or generated on demand. 2. Stream operations don't mutate their source. For example, the filter method does not remove elements from a new stream, but it yields a new stream in which they are not present. 3. Stream operations are lazy when possible. This means they are not executed until their result is needed. For example, if you only ask for the first five long words instead of all, the filter method will stop filtering after the fifth match. As a consequence, you can even have infinite streams!

What are differences between streams and collections?

- max/min methods Optional<String> largest = words.max(String::compareToIgnoreCase); The findFirst returns the first value in a nonempty collection. It is often useful when combined with filter. Optional<String> startsWithQ = words.filter(s -> s.startsWith("Q")).findFirst();

What are simple reduction method examples?

- close() - flush() - write()

What are some methods of OutputStream class?

by an error in JMV, error in program, or throw statement.

What are three ways that an exception can be generated?

Exception and Error

What are two direct subclasses of a Throwable?

Although the primitive-type buffer classes have similar capabilities, ByteBuffer is the largest and most versatile. After all, bytes are the basic unit used by operating systems to transfer data items.

What buffer implementation is most versatile?

An instance of the java.io.File class abstracts a file or directory path. This instance provides access to the file system to perform tasks on this path such as removing the underlying file or directory. new File("temp").mkdir();

What class abstracts a file or directory path?

An instance of the java.io.RandomAccessFile class provides random access to a file. RandomAccessFile raf = new RandomAccessFile("employees.dat", "r"); int empIndex = 10; raf.seek(empIndex * EMP_REC_LEN);

What class provides random access to a file?

JDK 1.0 introduced rudimentary I/O facilities for accessing the file system (to create a directory, remove a file, or perform another task), accessing file content randomly (as opposed to sequentially), and streaming byte-oriented data between sources and destinations in a sequential manner.

What classic I/O facilities did JDK 1.0 introduce?

The Stream interface has two static methods for making infinite streams. The generate method takes a function with no arguments (or, technically, an object of the Supplier<T> interface). Whenever a stream value is needed, that function is called to produce a value. You can get a stream of constant values as Stream<String> echos = Stream.generate(() -> "Echo"); or a stream of random numbers as Stream<Double> randoms = Stream.generate(Math::random); To produce infinite sequences, such as 0 1 2 3 . . . , use the iterate method instead. It takes a "seed" value and a function (technically, a UnaryOperator<T>) and repeatedly applies the function to the previous result. For example, Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

What do generate and iterate methods of Stream interface do?

c

What does AWT stands for? a) All Window Tools b) All Writing Tools c) Abstract Window Toolkit d) Abstract Writing Toolkit

FileOutputStream and FileInputStream have a performance problem. Each file output stream write() method call and file input stream read() method call results in a native method call to one of the underlying operating system's functions, and these native method calls slow down I/O. The concrete BufferedOutputStream and BufferedInputStream filter stream classes improve performance by minimizing underlying output stream write() and underlying input stream read() method calls. Instead, calls to BufferedOutputStream's write() and BufferedInputStream's read() methods take Java buffers into account: When a write buffer is full, write() calls the underlying output stream write() method to empty the buffer. Subsequent calls to BufferedOutputStream's write() methods store bytes in this buffer until it's once again full. When the read buffer is empty, read() calls the underlying input stream read() method to fill the buffer. Subsequent calls to BufferedInputStream's read() methods return bytes from this buffer until it's once again empty. BufferedOutputStream declares the following constructors: BufferedOutputStream(OutputStream out) creates a buffered output stream that streams its output to out. An internal buffer is created to store bytes written to out. BufferedOutputStream(OutputStream out, int size) creates a buffered output stream that streams its output to out. An internal buffer of length size is created to store bytes written to out.

What does BufferedOutputStream and BufferedInputStream do?

The concrete OutputStreamWriter class (a Writer subclass) is a bridge between an incoming sequence of characters and an outgoing stream of bytes. Characters written to this writer are encoded into bytes according to the default or specified character encoding. Each call to one of OutputStreamWriter's write() methods causes an encoder to be called on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The characters passed to the write() methods are not buffered. The concrete InputStreamReader class (a Reader subclass) is a bridge between an incoming stream of bytes and an outgoing sequence of characters. Characters read from this reader are decoded from bytes according to the default or specified character encoding. Each call to one of InputStreamReader's read() methods may cause one or more bytes to be read from the underlying input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.

What does OutputStreamWriter and InputStreamReader do?

Return a potentially empty array of strings naming the files and directories in the directory denoted by this File object's abstract path. If the path doesn't denote a directory, or if an I/O error occurs, this method returns null. Otherwise, it returns an array of strings, one string for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path. Also, there is no guarantee that the name strings in the resulting array will appear in alphabetical or any other order.

What does String[] list() method of the File class do?

Return true if and only if the file or directory that's denoted by this File object's abstract path exists.

What does exists() method of the File class do?

Unlike default/custom serialization/deserialization, externalization offers complete control over the serialization and deserialization tasks. Note Externalization helps you improve the performance of the reflection-based serialization and deserialization mechanisms by giving you complete control over what fields are serialized and deserialized. Java supports externalization via java.io.Externalizable.

What does externalization do?

the peek method yields another stream with the same elements as the original, but a function is invoked every time an element is retrieved. That is handy for debugging: Object[] powers = Stream.iterate(1.0, p -> p * 2) .peek(e -> System.out.println("Fetching " + e)) .limit(20).toArray(); When an element is actually accessed, a message is printed. This way you can verify that the infinite stream returned by iterate is processed lazily.

What does peek method do?

The call stream.skip(n) does the exact opposite of stream.limit(n): It discards the first n elements. This is handy when splitting text into words since, due to the way the split method works, the first element is an unwanted empty string. Stream<String> words = Stream.of(contents.split("\\PL+")).skip(1);

What does stream.skip(n) do?

The transient keyword prevents the values of instance fields that are declared with this keyword from being persisted when an object is serialized (written as a sequence of bytes to some destination). The values of such instance fields shouldn't be persisted and later restored when an object is deserialized (reconstituted from a sequence of bytes read from some source). For example, if your object has a field of type java.io.InputStream, you don't serialize this field's reference because the stream won't be open for input when you deserialize the object -- the stream source (e.g., a file) might not exist.

What does the transient keyword accomplish?

ll channels are instances of classes that ultimately implement the java.nio.channels.Channel interface. Channel declares the following methods: - void close(): Close this channel. When this channel is already closed, invoking close() has no effect. When another thread has already invoked close(), a new close() invocation blocks until the first invocation finishes, after which close() returns without effect. This method throws java.io.IOException when an I/O error occurs. After the channel is closed, any further attempts to invoke I/O operations on it result in java.nio.channels.ClosedChannelException being thrown. - boolean isOpen(): Return this channel's open status. This method returns true when the channel is open; otherwise, it returns false.

What interface do all channels implement?

Many operating systems allow streams to be configured to operate in nonblocking mode in which a thread continually checks for available input without blocking when no input is available. The thread can handle incoming data or perform other tasks until data arrives. This "polling for available input" activity can be wasteful, especially when the thread needs to monitor many input streams (such as in a web server context).

What is "polling for available input"?

Nonblocking mode improves performance by preventing a thread that performs a read or write operation on a channel from blocking until input is available or the output has been fully written. However, it doesn't let an application determine if it can perform an operation without actually performing the operation. For example, when a nonblocking read operation succeeds, the application learns that the read operation is possible but also has read some data that must be managed. This duality prevents you from separating code that checks for stream readiness from the data-processing code without making your code significantly complicated. Asynchronous I/O overcomes this problem by letting the thread initiate the operation and immediately proceed to other work. The thread specifies some kind of callback function that is invoked when the operation finishes.

What is Asynchronous I/O?

Modern operating systems offer sophisticated I/O services (such as readiness selection) for improving I/O performance and simplifying I/O. Java Specification Request (JSR) 51 was created to address these capabilities. JSR 51's description indicates that it provides APIs for scalable I/O, fast buffered binary and character I/O, regular expressions, and charset conversion. Collectively, these APIs are known as NIO.

What is NIO?

RandomAccessFile is useful for creating a flat file database, a single file organized into records and fields. A record stores a single entry (such as a part in a parts database) and a field stores a single attribute of the entry (such as a part number).

What is RandomAccessFile useful for?

Channels provide the ability to perform a single I/O operation across multiple buffers. This capability is known as scatter/gather I/O (and is also known as vectored I/O). In the context of a write operation, the contents of several buffers are gathered (drained) in sequence and then sent through the channel to a destination. These buffers are not required to have identical capacities. In the context of a read operation, the contents of a channel are scattered (filled) to multiple buffers in sequence; each buffer is filled to its limit until the channel is empty or until the total buffer space is used.

What is Scatter/Gather I/O?

To support I/O, Channel is extended by the java.nio.channels.WritableByteChannel and java.nio.channels.ReadableByteChannel interfaces: - WritableByteChannel declares an abstract int write(ByteBuffer buffer) method that writes a sequence of bytes from buffer to the current channel. This method returns the number of bytes actually written. It throws java.nio.channels.NonWritableChannelException when the channel was not opened for writing, java.nio.channels.ClosedChannelException when the channel is closed, java.nio.channels.AsynchronousCloseException when another thread closes the channel during the write, java.nio.channels.ClosedByInterruptException when another thread interrupts the current thread while the write operation is in progress (thereby closing the channel and setting the current thread's interrupt status), and IOException when some other I/O error occurs. - ReadableByteChannel declares an abstract int read(ByteBuffer buffer) method that reads bytes from the current channel into buffer. This method returns the number of bytes actually read (or -1 when there are no more bytes to read). It throws java.nio.channels.NonReadableChannelException when the channel was not opened for reading; ClosedChannelException when the channel is closed; AsynchronousCloseException when another thread closes the channel during the read; ClosedByInterruptException when another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt status; and IOException when some other I/O error occurs.

What is WritableByteChannel and ReadableByteChannel?

File locking lets a process prevent or limit access to a file while the process is accessing the file. Although file locking can be applied to an entire file, it is often narrowed to a smaller region. A lock ranges from a starting byte offset in the file and continues for a specific number of bytes.

What is a file locking?

A file system is an operating system component that manages data storage and subsequent retrieval.

What is a file system?

A file system stores data in files, which are stored in directories. Its file and directory objects are accessed by specifying paths, which are compact maps that locate and identify file system objects. Paths are either absolute or relative: - An absolute path is a path relative to the file system's root directory. It's expressed as the root directory symbol followed by a delimited hierarchy of directory names that ends in the target directory or file name. - A relative path is a path relative to some other directory. It's expressed similarly to an absolute path but without the initial root directory symbol. In contrast, it's often prefixed with one or more delimited ".." character sequences, where each sequence refers to a parent directory.

What is a path?

Relative path doesn't start with the root directory symbol; it's interpreted via information taken from another path.

What is a relative path?

A stream is an ordered sequence of bytes of an arbitrary length. Bytes flow over an output stream from an application to a destination and flow over an input stream from a source to an application.

What is a stream in Java?

As well as managing data elements stored in external arrays (via the wrap() methods), buffers can manage data stored in other buffers. When you create a buffer that manages another buffer's data, the created buffer is known as a view buffer. Changes made in either buffer are reflected in the other. View buffers are created by calling a Buffer subclass's duplicate() method. The resulting view buffer is equivalent to the original buffer; both buffers share the same data items and have equivalent capacities. However, each buffer has its own position, limit, and mark. When the buffer being duplicated is read-only or direct, the view buffer is also read-only or direct. ByteBuffer buffer = ByteBuffer.allocate(10); ByteBuffer bufferView = buffer.duplicate(); View buffers are also created by calling one of ByteBuffer's asxBuffer() methods. For example, LongBuffer asLongBuffer() returns a view buffer that conceptualizes the byte buffer as a buffer of long integers.

What is a view buffer?

The legacy File class suffers from various problems. For example, the renameTo() method doesn't work consistently across operating systems. Also, many of File's methods don't scale; requesting a large directory listing from a server could result in a hang. The new file system interface mentioned in JSR 203 fixes these and other problems.

What is an improved filesystem interface introduced in NIO.2?

Bytes flow over an input stream from a source to an application.

What is an input stream?

Bytes flow over an output stream from an application to a destination.

What is an output stream?

A stream transformation produces a stream whose elements are derived from those of another stream. - filter() - filter transformation yields a stream with those elements that match a certain condition. Stream<String> longWords = wordList.stream().filter(w -> w.length() > 12); - map() - Often, you want to transform the values in a stream in some way. Use the map method and pass the function that carries out the transformation. Stream<String> lowercaseWords = words.stream().map(String::toLowerCase); When you use map, a function is applied to each element, and the result is a new stream with the results. -flatMap() - yields a stream obtained by concatenating the results of applying mapper to the elements of this stream. (Note that each result is a stream.)

What is stream transformation?

Every serialized object has an identifier. The deserialization mechanism compares the identifier of the object being deserialized with the serialized identifier of its class (all serializable classes are automatically given unique identifiers unless they explicitly specify their own identifiers) and causes InvalidClassException to be thrown when it detects a mismatch. You can avoid the thrown InvalidClassException instance by adding a static final long serialVersionUID = long integer value; declaration to the class. The long integer value must be unique and is known as a stream unique identifier (SUID). During deserialization, the JVM will compare the deserialized object's SUID to its class's SUID. If they match, readObject() will not throw InvalidClassException when it encounters a compatible class change (such as adding an instance field). However, it will still throw this exception when it encounters an incompatible class change (such as changing an instance field's name or type).

What is stream unique identifier (SUID)?

Although getFreeSpace() and getUsableSpace() appear to be equivalent, they differ in the following respect: unlike getFreeSpace(), getUsableSpace() checks for write permissions and other operating system restrictions, resulting in a more accurate estimate.

What is the difference between getFreeSpace() and getUsableSpace methods of the File class?

The clear() method marks a buffer as empty whereas reset() changes the buffer's current position to the previously set mark, or throws InvalidMarkException when there's no previously set mark.

What is the difference between reset() and clear() methods on buffer?

An Optional<T> object is a wrapper for either an object of type T or no object. In the former case, we say that the value is present. The Optional<T> type is intended as a safer alternative for a reference of type T that either refers to an object or is null.

What is the optional type?

d

What is the output of this program if input given is "Hello stop World"? class Input_Output { public static void main(String args[]) throws IOException { string str; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { str = (char) obj.readLine(); System.out.print(str); } while(!str.equals("strong")); } } a) Hello b) Hello stop c) World d) Hello stop World

a

What is the output of this program if input given is "abc'def/'egh"? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c != '\''); } } a) abc' b) abcdef/' c) abc'def/'egh d) abcqfghq

a

What is the output of this program if input given is "abc'def/'egh"? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c!='\''); } } a) abc' b) abcdef/' c) abc'def/'egh d) abcqfghq

c

What is the output of this program if input given is 'abcqfghqbcd'? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c != 'q'); } } a) abcqfgh b) abc c) abcq d) abcqfghq

a

What is the output of this program? class output { public static void main(String args[]) { String a="hello i love java"; System.out.println(indexof('i')+" "+indexof('o')+" "+lastIndexof('i')+" "+lastIndexof('o') )); } } a) 6 4 6 9 b) 5 4 5 9 c) 7 8 8 9 d) 4 3 6 9

d

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello World"); s1.insert(6 , "Good "); System.out.println(s1); } } a) HelloGoodWorld b) HellGoodoWorld c) HellGood oWorld d) Hello Good World

a

What is the output of this program? class output { public static void main(String args[]) { char c[]={'a','1','b',' ','A','0']; for (int i = 0; i < 5; ++i) { if(Character.isDigit(c[i])) System.out.println(c[i]" is a digit"); if(Character.isWhitespace(c[i])) System.out.println(c[i]" is a Whitespace character"); if(Character.isUpperCase(c[i])) System.out.println(c[i]" is an Upper case Letter"); if(Character.isUpperCase(c[i])) System.out.println(c[i]" is a lower case Letter"); i = i + 3; } } } a) a is a lower case Letter is White space character b) b is a lower case Letter is White space characte c) a is a lower case Letter A is a upper case Letter d) a is a lower case Letter 0 is a digit

d

What is the output of this program? class output { public static void main(String args[]) { StringBuffer c = new StringBuffer("Hello"); StringBuffer c1 = new StringBuffer(" World"); c.append(c1); System.out.println(c); } } a) Hello b) World c) Helloworld d) Hello World

a

What is the output of this program? import java.io.*; class Chararrayinput { public static void main(String[] args) { String obj = "abcdef"; int length = obj.length(); char c[] = new char[length]; obj.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 3); int i; try { while((i = input2.read()) != -1) { System.out.print((char)i); } } catch (IOException e) { e.printStackTrace(); } } } a) abc b) abcd c) abcde d) abcdef

d

What is the output of this program? import java.io.*; class Chararrayinput { public static void main(String[] args) { String obj = "abcdefgh"; int length = obj.length(); char c[] = new char[length]; obj.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 1, 4); int i; int j; try { while((i = input1.read()) == (j = input2.read())) { System.out.print((char)i); } } catch (IOException e) { e.printStackTrace(); } } } a) abc b) abcd c) abcde d) None of the mentioned

c

What is the output of this program? import java.io.*; class filesinputoutput { public static void main(String args[]) { InputStream obj = new FileInputStream("inputoutput.java"); System.out.print(obj.available()); } } a) true b) false c) prints number of bytes in file d) prints number of characters in the file

d

What is the output of this program? import java.io.*; public class filesinputoutput { public static void main(String[] args) { String obj = "abc"; byte b[] = obj.getBytes(); ByteArrayInputStream obj1 = new ByteArrayInputStream(b); for (int i = 0; i < 2; ++ i) { int c; while((c = obj1.read()) != -1) { if(i == 0) { System.out.print(Character.toUpperCase((char)c)); obj2.write(1); } } System.out.print(obj2); } } } a) AaBaCa b) ABCaaa c) AaaBaaCaa d) AaBaaCaaa

1. Create a stream. 2. Specify intermediate operations for transforming the initial stream into others, possibly in multiple steps. 3. Apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used. List<String> words = ... long count = words.stream().filter(w -> w.length() > 12).count(); or you can use parallelStream() instead of stream() In the example, the stream is created with the stream or parallelStream method. The filter method transforms it, and count is the terminal operation.

What is the typical workflow when you work with streams?

Unlimited serialization is the process of serializing an entire object graph. Java doesn't support unlimited serialization for the following reasons: - Security: If Java automatically serialized an object containing sensitive information (such as a password or a credit card number), it would be easy for a hacker to discover this information and wreak havoc. It's better to give the developer a choice to prevent this from happening. - Performance: Serialization leverages the Reflection API, which tends to slow down application performance. Unlimited serialization could really hurt an application's performance. - Objects not amenable to serialization: Some objects exist only in the context of a running application and it's meaningless to serialize them. For example, a file stream object that's deserialized no longer represents a connection to a file.

What is unlimited serialization?

inputStream

What type of stream is System.in?

DataInputStream

What type of stream is used to read binary data?

What is a race condition?

When 2 or more threads are trying to access data at the same time. This can cause thread interference.

d

Which of these class contains the methods print() & println()? a) System b) System.out c) BUfferedOutputStream d) PrintStream

b

Which of these class contains the methods used to write in a file? a) FileStream b) FileInputStream c) BUfferedOutputStream d) FileBufferStream

a

Which of these class is implemented by FilterInputStream class? a) InputStream b) InputOutputStream c) BufferedInputStream d) SequenceInputStream

b

Which of these class is used to create an object whose character sequence is mutable? a) String() b) StringBuffer() c) Both of the mentioned d) None of the mentioned

a

Which of these class is used to read characters and strings in Java from console? a) BufferedReader b) StringReader c) BufferedStreamReader d) InputStreamReader

d

Which of these class is used to read from byte array? a) InputStream. b) BufferedInputStream. c) ArrayInputStream. d) ByteArrayInputStream.

a

Which of these classes are used by Byte streams for input and output operation? a) InputStream b) InputOutputStream c) Reader d) All of the mentioned

b

Which of these classes are used by character streams for input and output operations? a) InputStream b) Writer c) ReadStream d) InputOutputStream

b

Which of these classes are used by character streams output operations? a) InputStream b) Writer c) ReadStream d) InputOutputStream

a

Which of these exception is thrown by close() and read() methods? a) IOException b) FileException c) FileNotFoundException d) FileInputOutputException

c

Which of these exception is thrown in cases when the file specified for writing it not found? a) IOException b) FileException c) FileNotFoundException d) FileInputException

c

Which of these is a type of stream in Java? a) Integer stream b) Short stream c) Byte stream d) Long stream

a

Which of these is used to perform all input & output operations in Java? a) streams b) Variables c) classes d) Methods

d

Which of these is used to read a string from the input stream? a) get() b) getLine() c) read() d) readLine()

a

Which of these method of class StringBuffer is used to reverse sequence of characters? a) reverse() b) reverseall() c) Reverse() d) reverseAll()

b

Which of these methods are used to read in from file? a) get() b) read() c) scan() d) readFileInput()

d

Which of these methods can be used to writing console output? a) print() b) println() c) write() d) All of the mentioned

c

Which of these methods is used to write() into a file? a) put() b) putFile() c) write() d) writeFile()

c

Which of these values is returned by read() method is end of file (EOF) is encountered? a) 0 b) 1 c) -1 d) Null

Java's stream classes are good for streaming sequences of bytes, but they're not good for streaming sequences of characters because bytes and characters are two different things: a byte represents an 8-bit data item and a character represents a 16-bit data item. Also, Java's char and java.lang.String types naturally handle characters instead of bytes. More importantly, byte streams have no knowledge of character sets (sets of mappings between integer values, known as code points, and symbols, such as Unicode) and their character encodings (mappings between the members of a character set and sequences of bytes that encode these characters for efficiency, such as UTF-8). If you need to stream characters, you should take advantage of Java's writer and reader classes, which were designed to support character I/O (they work with char instead of byte). Furthermore, the writer and reader classes take character encodings into account.

Why do we need writers and readers?

Because File(String path), File(String parent, String child), and File(File parent, String child) don't detect invalid path arguments (apart from throwing a java.lang.NullPointerException when path or child is null), you must be careful when specifying paths. You should strive to only specify paths that are valid for all operating systems on which the application will run. For example, instead of hard-coding a drive specifier (such as C:) in a path, use a root returned from listRoots(), which I discuss later. Even better, keep your paths relative to the current user/working directory (returned from the user.dir system property).

Why only specify paths that are valid for all operating systems on which the application will run?

After filling a buffer, you must prepare it for draining by a channel. When you pass the buffer as is, the channel accesses undefined data beyond the current position. To solve this problem, you could reset the position to 0, but how would the channel know when the end of the inserted data had been reached? The solution is to work with the limit property, which indicates the end of the active portion of the buffer. Basically, you set the limit to the current position and then reset the current position to 0. You could accomplish this task by executing the following code, which also clears any defined mark: buffer.limit(buffer.position()).position(0); However, there's an easier way to accomplish the same task, as shown here: buffer.flip(); String[] poem = { "Roses are red", "Violets are blue", "Sugar is sweet", "And so are you." }; CharBuffer buffer = CharBuffer.allocate(50); for (int i = 0; i < poem.length; i++) { // Fill the buffer. for (int j = 0; j < poem[i].length(); j++) buffer.put(poem[i].charAt(j)); // Flip the buffer so that its contents can be read. buffer.flip(); // Drain the buffer. while (buffer.hasRemaining()) System.out.print(buffer.get()); // Empty the buffer to prevent BufferOverflowException. buffer.clear(); System.out.println(); }

Why to flip a buffer?

Regular expressions were introduced as part of NIO. Although you might wonder about the rationale for doing this (what have regular expressions got to do with I/O?), regular expressions are commonly used to scan textual data that is read from a file or other source. The need to perform these scans as quickly as possible mandated their inclusion.

Why were regular expressions introduced as part of NIO?

You would use FileInputStream to open an existing file and connect an input stream to it. You would then invoke various read() methods to read bytes from the file over the input stream. Lastly, you would invoke close() to close the stream and file. FileInputStream fis = null; try { fis = new FileInputStream("image.jpg"); // Read bytes from file. int _byte; while ((_byte = fis.read()) != -1) // -1 signifies EOF ; // Process _byte in some way. } catch (IOException ioe) { // Handle exception. } finally { if (fis != null) try { fis.close(); } }

Why would you use FileInputStream?

public static void main(String[] args) { ReadableByteChannel src = Channels.newChannel(System.in); WritableByteChannel dest = Channels.newChannel(System.out); try { copy(src, dest); } catch (IOException ioe) { System.err.println("I/O error: " + ioe.getMessage()); } finally { try { src.close(); dest.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } static void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(2048); while (src.read(buffer) != -1) { buffer.flip(); dest.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) dest.write(buffer); }

Write an example for channels and buffers

What is the output of this program if input given is "abc'def/'egh"? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c!='\''); } } a) abc' b) abcdef/' c) abc'def/'egh d) abcqfghq

a

What is the output of this program? class output { public static void main(String args[]) { String a="hello i love java"; System.out.println(indexof('i')+" "+indexof('o')+" "+lastIndexof('i')+" "+lastIndexof('o') )); } } a) 6 4 6 9 b) 5 4 5 9 c) 7 8 8 9 d) 4 3 6 9

a

What is the output of this program? class output { public static void main(String args[]) { char c[]={'a','1','b',' ','A','0']; for (int i = 0; i < 5; ++i) { if(Character.isDigit(c[i])) System.out.println(c[i]" is a digit"); if(Character.isWhitespace(c[i])) System.out.println(c[i]" is a Whitespace character"); if(Character.isUpperCase(c[i])) System.out.println(c[i]" is an Upper case Letter"); if(Character.isUpperCase(c[i])) System.out.println(c[i]" is a lower case Letter"); i = i + 3; } } } a) a is a lower case Letter is White space character b) b is a lower case Letter is White space characte c) a is a lower case Letter A is a upper case Letter d) a is a lower case Letter 0 is a digit

a

What is the output of this program? import java.io.*; class Chararrayinput { public static void main(String[] args) { String obj = "abcdef"; int length = obj.length(); char c[] = new char[length]; obj.getChars(0, length, c, 0); CharArrayReader input1 = new CharArrayReader(c); CharArrayReader input2 = new CharArrayReader(c, 0, 3); int i; try { while((i = input2.read()) != -1) { System.out.print((char)i); } } catch (IOException e) { e.printStackTrace(); } } } a) abc b) abcd c) abcde d) abcdef

a

Which of the following statement is correct? a) reverse() method reverses all characters. b) reverseall() method reverses all characters. c) replace() method replaces first occurrence of a character in invoking string with another character. d) replace() method replaces last occurrence of a character in invoking string with another character.

a

Which of these exception is thrown by close() and read() methods? a) IOException b) FileException c) FileNotFoundException d) FileInputOutputException

a

Which of these is used to perform all input & output operations in Java? a) streams b) Variables c) classes d) Methods

a

Files: a) contains only static methods b) contains static and non=static methods

a correct

Paths: a) creates Paths object that contain static methods b) creates Paths objects that contain non-static methods

a correct. creates Paths object that contain static methods static Path methods: *static Path get( String first, String... more)* - *Converts* a *path string*, or a sequence of strings that when joined form a path string, *to a Path*. *static Path get(URI uri)* - *Converts* the given *URI* to a *Path object*. Note: URI is Uniform Resource Identifier (URI) reference e.g. *opaque* URIs are: mailto:[email protected] news:comp.lang.java urn:isbn:096139210x *hierarchical* URIs are: http://java.sun.com/j2se/1.3/ docs/guide/collections/faq.html#28 ../../../demo/jfc/SwingSet2/src/SwingSet2.java file:///~/calendar

Which of the below can be created using "new": a) File b) Path c) Paths d) Files

a correct. *Path* is an *interface*. *Files* and *Paths* are *final classes*. These final classes *consists* exclusively of *static methods* that operate on files, directories, or other types of files.

import java.io.File; class A { public static void main( String[] args) { File f = new File("C:\\a\\b\\Log.txt" ); f.createNewFile(); } } The above code will give: a) compiler error b) runtime error c) compile and create a new file Log.txt d) none of the above

a correct. *compiler error* complains that method *createNewFile()*; should be placed in a *try catch block* or *main()* class should *declare* that it *throws Exception*

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println( i.createdirectory()); } Directory b does not exist. The above code will give: a) compiler error b) runtime error c) compile and print true. d) none of the above

a correct. *createdirectory()* is *not* a *method* within the *File class*. To create a new directory: call the method *mkdir()* or *mkdirs()* for the creation of subdirectories

import java.io.Console; class A { public static void main(String[] args) { Console c = System.console(); char[] n = c.readLine("%c", "Enter Name: "); System.out.println( "Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

a correct. *readLine*("%c", "Enter Name: "); *returns a String* var. *char[] n* = c.readLine(...); You *cannot store* variable as a *char* variable. ----> Compiler error. Solution: *String *n = c.readLine(*"%s"*, "Enter Name: "); or *String* n = c.readLine(*"Enter Name: "*);

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); char n = c.readPassword( "%c", "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and store user input to char n d) none of the above

a correct. *readPassword()* returns *char array* You *cannot store* (*char[]*) and read *in* a variable (*char*) ----> *compiler error.* Solution: *char[]* n = c.readPassword("%c", "Enter password: ");

File a = new File("c:\\a"); File b = new File("c:\\a\\b"); File f = new File(a,b,"f.txt"); System.out.println( f.createNewFile()); System.out.println(f.exists()); The folders exist and the file already exists. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

a correct. Remember *File constructor* can take params : new File(*File, String*) new File(*String*) new File(*String,String*) However, the following will not compile: new File(*a,b,"f.txt"*); gives *compiler error*

public static void main(String[] args) throws Exception { File i=new File("C:\\a\\b\\m.txt"); System.out.println( i.renameTo("C:\\a\\b\\a.txt")); } Assuming both files exist. The above code will give: a) compiler error b) runtime error c) compile and rename m.txt to a.txt d) none of the above

a correct. i.*renameTo()* *doesn't* take *string* parameter. Solution: *Wrap* the new file name *in* a *File object* i.e. i.renameTo( *new File("C:\\a\\b\\a.txt")*) Note: you can *also change folder* the same way. if *m.txt* does *not exist* then it does *not rename* the file and *returns false*

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println(i.del()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete b folder and return true d) none of the above

a correct. it will give a compiler error as the *del()* method does not exist* in *File*. Replace del() with *i.delete()* and it will *work*.

The set of all descendants of a node in a binary tree form

a subtree rooted at that node

in the generic type notation <T extends Number> to what type of bound is T constrained?

an upper bound

InputStream and OutputStream

are abstract classes that declare methods for performing byte-based input and output, respectively.

import java.io.Console; class A { public static void main(String[] args) { Console c = System.console(); char[] n =c.readPassword( "%s", "Enter password: "); System.out.println( "Password is: "+n); } } Consider the user entered mark. The above code will give: a) compiler error b) runtime error c) compile and print mark d) Address of password e.g. [C@139eeda

d is correct. Password chars are *encrypted* with the method *readPassword*( "%s", "Enter password: ");

public static void main(String[] args) throws Exception { File i = new File("C:\\a\\b\\"); i.mkdir(); System.out.println( i.isDirectory()); } Assume folders "a" and "b" do not exist prior to execution. The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

d is correct. *i.mkdir();* doesn't create folders it *makes one folder only*. however if i.mkdir(); is replaced with *i.mkdirs();* this would *work fine*.

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a1"); bw.write("b1"); } Where "myFile.txt" already exists in folder "a". The above code will give: a) compiler error b) runtime error c) compile and print "a1b1" d) none of the above

d is correct. *myFile.txt* is still *open*. You must call *bw.flush();* *bw.close();* *after* completing *writing* to the *file*. Note: If the *bw.flush();* and *bw.close();* were in the original code then the *file* would be *completely overwritten* with "a1b1"

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println(i.delete()); System.out.println(i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

d is correct. It *deletes b subfolder* and *returns true*. The *second call* to the delete method *i.delete()* attempts to *delete* the *same* subfolder *b* but it *does not exist* therefore returns* false*

import java.io.File; class A { public static void main(String[] args) throws Exception { File dir =new File("C:\\a\\b\\"); dir.mkdirs(); File f = new File(dir,"MyFile.txt"); } } The above code will give: a) compiler error b) runtime error c) compile and print create an empty file "MyFile.txt" in a\b folder d) none of the above

d is correct. It will *create* the *folders a* and *b* but *not* the file "*MyFile.txt*" f.*createNewFile()* should be *declared after:* *File f=new File(dir, "MyFile.txt");*

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); File f =new File(i,"m.txt"); System.out.println(f.isFile()); } Assuming "m.txt" does not exist. The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

d is correct. It will return false. You need to call the method *f.createNewFile();* *after:* File f = new File(i,"m.txt"); it will then *create* the file "*m.txt*" and return *true*

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write("b"); bw.flush(); bw.close(); } Where "myFile.txt" does not exist but folder "a" does. The above code will give: a) compiler error b) runtime error c) compile and write a b (On separate lines) d) none of the above

d is correct. Will *write* "ab" (without spaces). To *write a* and *b* on *separate lines* you need to *get* the *character* for your particular operating system e.g. bw.write("a"); bw.write( *System.lineSeparator()*); bw.write("b"); Note: If "myFile.txt" *does not exist*, it gets *created* and then *written* to it. This is *provided* the *folder* does *exist*. If "myFile.txt" *does exist* then *all contents* get *erased* and the *file is *completely overwritten* with "ab" on same line. If *folder* does *not exist* then a *run time error* will be *thrown*: java.io.*FileNotFoundException*

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println(i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

d is correct. it will *delete b sub folder* only.

15.1 Q1: Which of the following statements is false? a. Storage of data variables and arrays is temporary. b. Data is lost when a local variable "goes out of scope." c. Files are used for long-term retention of large amounts of data. d. Data maintained in files is often called transient data.

d. Data maintained in files is often called transient data.

15.2 Q1: Which of the following classes is not used for file input? a. FileInputStream b. FileReader c. ObjectInputStream d. Formatter

d. Formatter

Which of the following classes is not used for file input? a. FileInputStream b. FileReader c. ObjectInputStream d. Formatter

d. Formatter

15.4.1 Q1: Which statement regarding Java files is false? a. Java imposes no structure on a file. b. Notions like "record" do not exist in Java files. c. The programmer must structure files to meet the requirements of applications. d. Records in a Java sequential file are stored in order by record key.

d. Records in a Java sequential file are stored in order by record key.

15.4.1 Q2: When all the contents of a file are truncated, this means that ________. a. the data in the file is saved to a backup file b. the file is deleted c. a FileNotFoundException occurs d. all the data in the file is discarded

d. all the data in the file is discarded

When all the contents of a file are truncated, this means that ________. a. the data in the file is saved to a backup file b. the file is deleted c. a FileNotFoundException occurs d. all the data in the file is discarded

d. all the data in the file is discarded.

________ is an I/O-performance-enhancement technique—it reduces the number of I/O operations by combining smaller outputs together in memory; the number of physical I/O operations is much smaller than the number of I/O requests issued by the program. a. Aggregating b. Accumulating c. Amassing d. Buffering

d. buffering

If you do not want to wait until all the bytes you need are immediately available, you can use the _____________ method to determine how many bytes can be read without blocking

available()

What is the output of this program? class output { public static void main(String args[]) { StringBuffer c = new StringBuffer("Hello"); System.out.println(c.length()); } } a) 4 b) 5 c) 6 d) 7

b

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello"); StringBuffer s2 = s1.reverse(); System.out.println(s2); } } a) Hello b) olleH c) HelloolleH d) olleHHello

b

Which of these class contains the methods used to write in a file? a) FileStream b) FileInputStream c) BUfferedOutputStream d) FileBufferStream

b

Which of these classes are used by character streams output operations? a) InputStream b) Writer c) ReadStream d) InputOutputStream

b

Which of these methods are used to read in from file? a) get() b) read() c) scan() d) readFileInput()

b

Paths is located in: a) java.io.file.Paths. b) java.nio.file.Paths

b correct

Files is an: a) abstract class b) final class c) class d) interface

b correct.

Files and Path and Paths: a) can be created using "new" b) cannot be created using "new"

b correct. *Path* is an *interface*. *Files* and *Paths* are *final classes*. These final classes consists exclusively of *static methods* that operate on files, directories, or other types of files.

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); String n = c.readLine("%c", "Enter Name: "); System.out.println( "Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

b correct. String n = c.readLine( "*%c*", "Enter Name: "); Throws *java.util.IllegalFormatConversionException* Attempting to *convert char c* formatted type *to string n* throws *exception*. Solution: c.readLine( "*%s*", "Enter Name: ");

import java.io.File; class B { public static void main(String[] args) throws Exception { File f = new File( "c:\\a\\b\\MyFile.txt"); System.out.println(f.exists()); System.out.println( f.createNewFile() ); } } Assume the above path does not exist. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

b correct. Will print "false *java.io.IOException*: The system cannot find the path specified"

import java.io.File; class A { public static void main(String[] args) throws Exception { File dir = new File("C:\\a\\b\\"); File f=new File(dir, "MyFile.txt"); f.createNewFile(); } } Considering the above directories a and b do not exist prior to execution. The above code will give: a) compiler error b) runtime error c) compile and print create an empty file "MyFile.txt" in a\b folder d) none of the above

b correct. f.*createNewFile()*; will *throw an IOException* As *directories* *a* and *b* do *not exist* prior to execution Solution: *insert:* dir.*mkdirs()*; AFTER *File dir* = new File("C:\\a\\b\\"); i.e. File dir = new File("C:\\a\\b\\"); *dir.mkdirs();* File f=new File(dir, "MyFile.txt"); f.createNewFile();

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); char[] pw =c.readPassword( null, "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and print "Enter password: " d) none of the above

b is correct. It will *throw* an *NullPointerException*. replace: readPassword(*null*,"Enter password: "); with: readPassword(*"%s"*,"Enter password: "); or readPassword(* "Enter password: *"); and it will *compile* and run *fine*.

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get( "file:///C://a//File.txt"); System.out.println(p1); } } Consider the above code running on Windows. The above code will give: a) compiler error b) runtime error c) compile and print C://a//File.txt d) none of the above

b is correct. Will throw *InvalidPathException* because *file:///C://a//* on Windows is a URL. Solution: *Convert* the string to *URI Universal Resource Identifier*- Path p1 = Paths. get( *URI.create*( "file:///C://a//File.txt")); making sure to *import java.net.URI*;

15.5 Q1: Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter a. A and B. b. C and D. c. C, D, E, F. d. E and F.

b. C and D.

15.3 Q1: Which of the following statements is false? a. A Path represents the location of a file or directory. b. Path objects open files and provide file-processing capabilities. c. Class Paths is used to get a Path object representing a file or directory location. d. The static method get of class Paths converts a String representing a file's or directory's location into a Path object.

b. Path objects open files and provide file-processing capabilities. Actually, Path objects do not open files nor do they provide any file-processing capabilities. They specify only the location of a file or directory.

Which of the following statements is false? a. InputStream and OutputStream are abstract classes for performing byte-based I/O. b. Tubes are synchronized communication channels between threads. c. A filter stream provides additional functionality, such as aggregating data bytes into meaningful primitive-type units. FilterInputStream and FilterOutputStream are typically extended, so some of their filtering capabilities are provided by their concrete subclasses. d. A PrintStream performs text output. System.out and System.err are PrintStreams.

b. Tubes are synchronized communication channels between threads.

Which of the following statements is false? a. With a BufferedOutputStream each output operation is directed to a buffer large enough to hold the data of many output operations. Transfer to the output device is performed in one large physical output operation when the buffer fills. b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method. c. With a BufferedInputStream, many "logical" chunks of data from a file are read as one large physical input operation into a memory buffer. d. With a BufferedInputStream, as a program requests data, it's taken from the buffer. When the buffer is empty, the next actual physical input operation is performed.

b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method.

A(n) ________ path starts from the directory in which the application began executing. a. absolute b. relative c. parallel d. comparative

b. relative

15.3 Q4: A(n) ________ path starts from the directory in which the application began executing. a. absolute b. relative c. parallel d. comparative

b. relative.

This sorting algorithm makes several passes through an array and causes the larger values to gradually move towards the end of the array with each pass

bubble sort

BufferedInputStream

buffers data

What does AWT stands for? a) All Window Tools b) All Writing Tools c) Abstract Window Toolkit d) Abstract Writing Toolkit

c

What is the output of this program if input given is 'abcqfghqbcd'? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c != 'q'); } } a) abcqfgh b) abc c) abcq d) abcqfghq

c

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello"); s1.setCharAt(1,x); System.out.println(s1); } } a) xello b) xxxxx c) Hxllo d) Hexlo

c

What is the output of this program? import java.io.*; class filesinputoutput { public static void main(String args[]) { InputStream obj = new FileInputStream("inputoutput.java"); System.out.print(obj.available()); } } Note: inputoutput.java is stored in the disk. a) true b) false c) prints number of bytes in file d) prints number of characters in the file

c

Which of these class is used to read from a file? a) InputStream b) BufferedInputStream c) FileInputStream d) BufferedFileInputStream

c

Which of these exception is thrown in cases when the file specified for writing it not found? a) IOException b) FileException c) FileNotFoundException d) FileInputException

c

Which of these is a type of stream in Java? a) Integer stream b) Short stream c) Byte stream d) Long stream

c

Which of these methods is used to write() into a file? a) put() b) putFile() c) write() d) writeFile()

c

Which of these values is returned by read() method is end of file (EOF) is encountered? a) 0 b) 1 c) -1 d) Null

c

Paths is an: a) abstract class b) static class c) class d) interface

c correct

Path contains: a) only static methods b) static and nonstatic methods c) nonstatic methods only

c correct.

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); String n = c.readLine("%s", "Enter Name: "); System.out.println( "Welcome "+n); } } The above code will give: a) compiler error b) runtime error c) compile and echo whatever you entered to the screen d) none of the above

c correct. e.g. c:> *java A * c:> *Enter Name:* Mark c:> Welcome Mark

import java.io.File; class B { public static void main(String[] args) throws Exception { File f = new File( "c:\\a\\b\\MyFile.txt"); System.out.println( f.exists()); System.out.println( f.createNewFile()); } } Assume the above path does exist. The above code will give: a) compiler error b) runtime error c) Compile and Print "false true" d) None of the above

c correct. It's important to ensure that the path/folders *exist beforehand*. *f.exists()* --> returns false. *f.createNewFile()* --> returns true when MyFile.txt successfully created

import java.nio.file.*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } } Where log2.txt does not exist but log1.txt doe exist. The above code will give: a) compiler error b) runtime error c) compile and copy the content successfully d) none of the above

c correct. compile and copy the content successfully Note: if *log2.txt* already *exists* it will *throw* a *FileAlreadyExistsException*. It the file to be written to *must not exist* prior to *copy*.

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); char[] pw =c.readPassword( "%s", "Enter password: "); } } The above code will give: a) compiler error b) runtime error c) compile and print "Enter password: " d) none of the above

c is correct.

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileReader fr =new FileReader(f); BufferedReader br = new BufferedReader(fr); System.out.println( br.readLine()); br.close(); } considering "hello world" is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

c is correct. Note: *File* object f needs to be *wrapped* in *FileReader* fr object which needs to be *wrapped* in *BufferedReader* br object in order to compile i.e. *File* wrapped in *FileReader* wrapped in *BufferedReader* e.g. File *f* = new File("C:\\a\\ myFile.txt"); FileReader *fr* = new FileReader(*f*); BufferedReader br = new BufferedReader(*fr*); otherwise compiler error.

public static void main(String[] args) throws Exception { File i= new File("C:\\a\\b\\m.txt"); System.out.println( i.renameTo( new File("C:\\a\\b\\a.txt"))); } Assuming both files exist. The above code will give: a) compiler error b) runtime error c) compile and rename m.txt to a.txt d) none of the above

c is correct. if *m.txt* does *not exist* then it does *not rename* the file and *returns false*

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println(i.isDirectory()); } Assume folders "a" and "b" do not exist prior to execution. The above code will give: a) compiler error b) runtime error c) compile and print false d) compile and print true

c is correct. File i = *new File("C:\\a\\b\\");* is an *object* *not* a *folder*. In order to *create* the *folder* you need to state: *File i* = new File("C:\\a\\b\\"); *i.mkdirs();* System.out.println( i.isDirectory()); ----> will return *true*

import java.nio.file.*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Path des = Paths.get( "C:\\a\\log2.txt"); Files.copy(src, des); } } Where log1.txt does not exist but log2.txt does exist. The above code will give: a) compiler error b) runtime error c) compile and will copy the contents of log1.txt to log2.txt d) none of the above

c is correct. Note: *if log2.txt does exists* then it will *throw* a *FileAlreadyExistsException* Solution: *delete log2.txt* in the folder location and it *will* then *create* a *new log2.txt* and copy the contents of log1.txt to log2.txt

import java.io.File; class A { public static void main( String [] args) { File f =new File( "C:\\a\\b\\"); f.mkdirs(); } } The above code will give: a) compiler error b) runtime error c) compile and create the subfolders a and b d) none of the above

c is correct. Note: The *main()* method does *not need* to *declare* that it *throws Exception* But *it does* if creating *via* import *java.nio.file.Files*; i.e. File f = new File( "C:\\a\\b\\*Log.txt*"); f.*createNewFile()*;

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("C:\\a\\","b\\File.txt"); System.out.println(p1); } } File location does not exist physically in memory. The above code will give: a) compiler error b) runtime error c) compile and print "C:\\a\\b\\File.txt" d) none of the above

c is correct. Paths.get( *"C:\\a\\*","*b\\File.txt*"); is *syntactically correct.* You can also use: Paths.get( "*C:\\a\\*", "*b\\*","*File.txt*"); or Path p1 = Paths.get( "*C:\\a\\b\\*","*File.txt*");

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); System.out.println(i.delete()); System.out.println(i.delete()); i = new File("C:\\a\\"); System.out.println(i.delete()); } Assume the above folders exist. The above code will give: a) compiler error b) runtime error c) compile and delete a and b folders and return true d) none of the above

c is correct. The *first delete()* method call *delete subfolder b*. A *File reference i* is then *reappointed* to a *new File Object* containing folder a. The *second delete() method call* then *deletes* this folder* a*.

public static void main(String[] args) throws Exception { File i =new File("C:\\a\\b\\"); File f =new File(i,"m.txt"); f.createNewFile(); System.out.println(f.createNewFile()); } Assuming "m.txt" does exist. The above code will give: a) compiler error b) runtime error c) compile and print true d) none of the above

c is correct. This code *creates a new file* in the *subdirectory b*

15.3 Q3: Which of the following statements is false? a. A DirectoryStream enables a program to iterate through the contents of a directory. b. Character-based input and output can be performed with classes Scanner and Formatter. c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory. d. Every file or directory on a disk drive has the same root directory in its path.

c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory. Actually, an absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory.

15.4.3 Q1: Which of the following statements is true? a. Class Scanner provides the ability to reposition to the beginning of a file with method seek. b. Class Scanner provides the ability to reposition to the beginning of a file with method reposition. c. Class Scanner does not provide the ability to reposition to the beginning of the file. d. If it is necessary to read a sequential file again, the program can simply keep reading—when the end of the file is reached, the Scanner is automatically set to point back to the beginning of the file.

c. Class Scanner does not provide the ability to reposition to the beginning of the file.

15.5.1 Q2: Instance variables that are not to be output with a Serializable object are declared using which keyword? a. private b. ignoreme c. transient d. persistent

c. transient

Instance variables that are not to be output with a Serializable object are declared using which keyword? a. private b. ignoreme c. transient d. persistent

c. transient

File streams

can be used to input and output data as bytes or characters

The stack empty operation

checks to see if there is at least one item on the stack

two collect terminal operations

collect(Collector collector) collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) e.g. HashSet<String> result = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);

how to create parallelism in stream

collection.parallelStream() stream.parallel()

Java's native character set is

the UTF-16 encoding of Unicode

Filtering

the filter stream provides additional functionality, such as aggregating bytes into meaningful primitive-type units.

In a list implementation of a queue, the end of the list from which elements are removed is called

the front of the queue

The getSelectedIndex method returns

the index of the selected item and -1 if no item is selected.

This method reads a single byte of data from the input stream's source and returns it as an int from 0 to 255.

the noargs "read()" method

To force the JFrame that encloses a window to resize itself automatically when a larger object is placed in the frame, use

the pack method

When a node with two children is removed from a binary search tree, it can be replaced with

the smallest node in its right subtree

In a list implementation of a stack, the end of the list at which elements are added and removed is called

the top of the stack

These data types are comprised of eight bytes:

unsigned byte and signed byte They're both made up of eight bits, and when you write an int onto a network connection using write(int b), only eight bits are placed on the wire. If an int outside the range 0-255 is passed to write(int b), the least significant byte of the number is written and the remaining three bytes are ignored. (This is the effect of casting an int to a byte.)

OutputStream's fundamental method is:

write(int b) This method takes an integer from 0 to 255 as an argument and writes the corresponding byte to the output stream. Take note that although this method takes an int as an argument, it actually writes an unsigned byte. Java doesn't have an unsigned byte data type, so an int has to be used here instead.

DataInputStream and RandomAccessFile

each implement this interface to read sets of bytes and process them as primitive-type values.

A binary tree is a collection of nodes in which

each node has at most one predecessor and at most two successors

In File class flush() frees up expensive operating system resources. True or false

false. *flush() guarantees* last *data* gets *written* to *disk*. *close() frees* up expensive operating system *resources*.

Files Path and Paths existed in Java 6. True or false

false. All were created in *Java 7*. Only *File* existed in *Java 6*

Compilers less than Java 7 uses static methods on File to create files and directories. True or false

false. Compilers <Java 7 use *instance methods* on File to *create files* and *directories*. e.g. File f = new File("C:\\a\\b\\Log.txt"); f.*mkdirs()*; f.*createNewFile()*;

Console is located in java.lang.console true or false

false. Console is located in* java.io.*Console

Java 7 Compilers use instance methods in Paths to create files and directories. True or false

false. Java 7 Compilers use *static methods* in *Paths* to create files and directories. e.g. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main( String[] args) { Path p = Paths.*get*("C:\\a\\b\\Log.txt"); Files.*createFile*(p);} } Note: Compilers <Java 7 uses *instance methods* on File to *create files* and *directories*. e.g. File f = new File("C:\\a\\b\\Log.txt"); f.mkdirs(); f.*createNewFile()*;

secondary storage devices

hard disks, flash drives, DVDs and more

A binary tree is a collection of items in which each item

has at most two successors

Complete the following code to create an empty file using only java.nio.file; for "C:\\a\\b\\Log.txt" file import java.nio._____._____; import java.nio._____._____; import java.nio._____._____; class A { public static void main( String[] args) { Path p = _____.get("C:\\a\\b\\Log.txt"); Files._____(p);} }

import *java.nio.file.Files*; import *java.nio.file.Path*; import *java.nio.file.Paths*; class A { public static void main( String[] args) { Path p = Paths.get("*C:\\a\\b\\Log.txt*"); Files.*createFile(p)*;} }

Fill in the below blanks to enable the file path to be printed to screen on Windows OS import java._____ ._____ ; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get(_____ ._____ ( "file:///C://a//File.txt")); System. out. println(p1); } }

import java.*net.URI*; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths. get(*URI.create*( "file:///C://a//File.txt"*)*); System.out.println(p1); } } This results in *C:\a\File.txt* getting *printed screen* Note: URI is Uniform Resource Identifier (URI) reference e.g. *opaque* URIs are: mailto:[email protected] news:comp.lang.java urn:isbn:096139210x *hierarchical* URIs are: http://java.sun.com/j2se/1.3/ docs/guide/collections/faq.html#28 ../../../demo/jfc/SwingSet2/src/SwingSet2.java file:///~/calendar

Complete the below code that copies the contents of log1.txt to log2.txt (where log2.txt does not exist) import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = _____ ._____ ( "C:\\a\\log1.txt"); _____ des = _____ ._____ ( "C:\\a\\log2.txt"); _____ ._____ (src, des); } }

import java.*nio.file*.Files; import java.*nio.file*.Path; import java.*nio.file.Paths*; class A { public static void main ( String[] args) throws Exception { Path src = *Paths.get*("C:\\a\\log1.txt"); *Path* des = *Paths.get*( "C:\\a\\log2.txt"); *Files.copy*(src, des); } }

Complete the below code that deletes the file log1.txt import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get( "C:\\a\\log1.txt"); Files.delete(src); }

import java.*nio.file.*Files; import java.*nio.file.*Path; import java.*nio. file.Paths*; class A { public static void main ( String[] args) throws Exception { Path src = Paths.get("*C:\\a\\log1.txt*"); Files.delete(src); }

Complete the below code that copies the contents of log1.txt to log2.txt import java._____ ._____ .Files; import java._____ ._____ .Path; import java._____ ._____ ._____ ; class A { public static void main ( String[] args) throws Exception { Path src = _____ ._____ ( "C:\\a\\log1.txt"); _____ des = _____ ._____ ( "C:\\a\\log2.txt"); _____ ._____ (src, des); } }

import java.*nio.file.*Files; import java.*nio.file.*Path; import java.*nio.file.Paths*; class A { public static void main ( String[] args) throws Exception { Path src = *Paths.get*("C:\\a\\log1.txt"); *Path* des = *Paths.get*("C:\\a\\log2.txt"); *Files.copy*(src, des); } }

Byte Streams : FileInputStream and FileOutputStream Example

import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }

Fill in the blanks to write the string Hello to the file f.txt (Assume the file exists). import ___.___.*; class B { public static void main(String[] args) throws Exception { File a = new File("c:\\a\\f.txt"); FileWriter writer = _______; writer._______("Hello"); writer.________; writer._________; } }

import java.io.*; class B { public static void main(String[] args) throws Exception { File a = new File("c:\\a\\f.txt"); FileWriter writer = *new FileWriter(a)*; writer.*write*("Hello"); writer.*flush*(); writer.*close*(); } }

Using BufferedReader and FileReader fill in the blanks below to read the first line within the file myFile.txt import java.io._____ ; import java.io._____ ; import java.io._____ ; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); _____ fr = new _____ (f); _____ br = new _____ (fr); System. out. println(br._____ ()); } }

import java.io.*BufferedReader*; import java.io.*File*; import java.io.*FileReader*; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); *FileReader* fr = new *FileReader(f)*; *BufferedReader* br = new *BufferedReader(fr)*; System.out.println( br.*readLine()*); } }

Fill in the blanks below to create a new file "MyFile.txt" within the newly created directories a\b import java.io._____ ; class A { public static void main(String[] args) throws Exception { _____ dir = new _____("C:\\a\\b\\"); dir._____ (); _____ f =new ____(dir,"MyFile.txt"); _____ . _____ (); } }

import java.io.*File*; class A { public static void main(String[] args) throws Exception { *File* dir=new *File*("C:\\a\\b\\"); dir.*mkdirs*(); *File* f=new *File*(dir, "MyFile.txt"); *f.createNewFile()*;} } Note: *createNewFile()* must be wrapped in a *try catch block* or the method must declare the it *throws an Exception*

Fill-in the below spaces which writes text to a file named "myFile.txt" (one line at a time). Note: "myFile.txt" exists. import java.io.____; import java.io._____; import java.io. ____; class A { public static void main( String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); ______ i = new _____(f); ______ j = new _____(i); j.println("Hello2"); j.println("World2"); j.flush(); j.close(); } }

import java.io.*File*; import java.io.*FileWriter*; import java.io.*PrintWriter*; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); *FileWriter* i=new *FileWriter*(f); *PrintWriter* j= new *PrintWriter*(i); j.println("Hello2"); j.println("World2"); j.flush(); j.close(); } } Note: Difference between *PrintWriter* and *BufferedWriter* *PrintWriter*- To get access to the *printXXX* methods (like *println(int)*) like you would use *System.out* to *write* to the *console*. *BufferedWriter* - *Efficient* way to *write* to a file as it *buffers characters* in Java *memory* before dropping to C to do the writing to the file.

Complete the code below to convert File f into the Path new class. import java.io._____ ; import java.nio._____ ._____ ; class A { public static void main(String[] args) { File f = new File("C:\\a\\b"); _____ p = f._____ (); System. out. println(p); } }

import java.io.*File*; import java.nio.*file.Path*; class A { public static void main(String[] args) { File f =new File("C:\\a\\b"); *Path* p =f.*toPath*(); System.out.println(p); } } Used to get Path with compiler less than Java 7

Complete the code below to convert Path p into the old File object. import java.io._____ ; import java.nio._____ ._____ ; class A { public static void main(String[] args) { Path p = Paths.get("C:\\a\\b"); _____ f2 = p._____ (); System. out. println(f2); } }

import java.io.*File*; import java.nio.*file.Path*; class A { public static void main(String[] args) { Path p =Paths.get("C:\\a\\b"); *File* f2 = p.*toFile*(); System.out.println(f2); } }

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); char[] pw =c.readPassword( "Enter password: "); System.out.println(___); } } Consider the user entering "Hello". fill-in the code to output what the user entered to the screen.

import java.io.Console; class A { public static void main(String[] args) { Console c =System.console(); char[] *pw*=c.readPassword( "Enter password: "); System.out.println(*pw*); } } Simply *prints* the *char array* to the screen. e.g. prompt> *Enter password:* *hello* After typing the string and pressing return it prints to the screen.

Complete the following to check if a file exists using only java.io.File; C:\\a\\b\\log.txt import java.io._____; class A { public static void main( String [] args) { _____f = new _____("C:\\a\\b\\log.txt"); System.out.println( f._____()); } }

import java.io.File; class A { public static void main( String [] args) { File f = new File("*C:\\a\\b\\log.txt*"); System.out.println( f.*exists()*); } } Will return true if file exists

Complete the following to create an empty directory using only java.io.File; for "C:\\a\\b\\" folders import java.io._____; class A { public static void main( String[] args) { File f =new _____("C:\\a\\b\\"); f._____(); } }

import java.io.File; class A { public static void main( String[] args) { File f =new File("*C:\\a\\b\\*"); f.*mkdirs()*; } } Note: The *main()* method *does not* need to declare that it *throws Exception* only when using certain File methods like *f.createNewFile()*

This is when method A calls method B, which calls method A.

indirect recursion

relative path

is "relative" to another directory, for example, a path relative to the directory in which the application began executing.

Uniform Resource Identifier (URI)

is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.

Buffering

is an I/O-performance-enhancement technique

A Java collection

is an object that is is used as a container for other objects

convert Stream to primitive stream

mapToInt(ToIntFunction<? super T> mapper) mapToLong(ToLongFunction<? super T> mapper) mapToDouble(ToDoubleFunction<? super T> mapper)

Collectors.mapping

mapping(Function, Collector)

mkdir( )

method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

mkdirs()

method creates both a directory and all the parents of the directory.

When writing a string to a binary file or reading a string from a binary file, it is recommended that you use

methods that use UTF-8 encoding

SecurityException

occurs if the user does not have permission to write data to the file

A race condition occurs when the correctness of a computation depends on the:

relative timing or interleaving of multiple threads at runtime

In this sorting algorithm, the smallest value in the array is located and moved to position 0. Then the next smallest value is located and moved to position 1. This process continues until all of the elements have been placed in their proper order.

selection sort

This search algorithm steps sequentially through an array, comparing each item with the search value.

sequential search

This search algorithm will search half the array on average.

sequential search

3 stream intermediate operations for transformation

filter(Predicate<? super T> predicate) map(Function<? super T, ? extends R> mapper) flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) e.g. List<String> zero = Arrays.asList(); List<String> one = Arrays.asList("Bonobo"); List<String> two = Arrays.asList("Mama Gorilla", "Baby Gorilla"); Stream<List<String>> animals = Stream.of(zero, one, two); animals.flatMap(l -> l.stream()).forEach(System.out::println);

Common operations

filter, map, reduce, find, match, sort, etc

FilterInputStream

filters an InputStream

FilterOutputStream

filters an OutputStream.

A/An ______ block will still execute even if it is placed after a return statement

finally

We typically use a/an ______ block to execute final clean up commands when using a try/catch block

finally

In Java 6 and earlier, it's wise to close a stream in a _______ _______.

finally block (sometimes called the dispose pattern)

Always ______ and close your buffered streams

flush

If we want to clear the data in a buffer, we need to use the ______ method

flush

A binary search tree is structured in such a way that

for each node, the left child holds a value that is less than the node, and the right child holds a value that is greater

If we want to read data from a client Socket, we must first call the ______ method on that Socket

getInputStream()

If we want to write data to a client Socket, we must first call the ______ method on that Socket

getOutputStream()

collectors - groupingBy

groupingBy(Function<T, K> classifier) groupingBy(Function<T, K> classifier, Collector downstream) groupingBy(Function<T,K> classifier, Supplier<M> mapFactory, Collector downstream) e.g. Map<String, List<Locale>> countryToLocales = locales.collect(Collectors.groupingBy(Locale::getCountry)); Map<String, City> stateToLargestCity = cities.collect(groupingBy(City::getState, maxBy(Comparator.comparing(City::getPopulation))));

The method findMax shown below is supposed to return the position of the largest value in the portion of an array between 0 and last, inclusive: int findMax(int array[ ], int last) { int maxPos = 0; for (int k = 1; k <= last; k++) { // Code is Missing } return maxPos; } The missing code is

if (array[k] > array[maxPos]) maxPos = k;

A list can be considered a recursive data structure because

if you remove the head of the list, what remains is also a list

The code executed by the method run() depends on the:

implementation provided for run() in a derived class

What do you need to import to use File FileWriter FileReader BufferedReader BufferedWriter PrintWriter in your code

import *java.io.**;

Complete the following code to create an empty file using only java.io.File; for "C:\\a\\b\\Log.txt" folders: import java.io._____; class A { public static void main(String[] args) throws Exception { _____f = new _____("C:\\a\\b\\Log.txt"); f._____(); } }

import *java.io.File;* class A { public static void main(String[] args) *throws Exception* { File f = new File("*C:\\a\\b\\Log.txt*"); f.*createNewFile();* } } Note: *createNewFile()* must be wrapped in a *try catch block* or the method must declare the it *throws an Exception*

Complete the following to create an empty directory using with java.nio.file; for C:\\a\\b\\ import java._____._____._____; import java._____._____._____; import java._____._____.Paths; class A { public static void main( String [] args) throws Exception { Path p=_____._____( "C:\\a\\b\\"); Files._____(p); } }

import *java.nio.file.Files*; import *java.nio.file.Path*; import *java.nio.file.Paths*; class A { public static void main( String [] args) throws Exception { Path p=Paths.get( "*C:\\a\\b\\*"); Files.*createDirectories*(p); } } Note: it's best to *declare* that the *main() method throws Exception* when dealing *createDirectories*(p);

Complete the following to create an empty directory using only java.io.File; for C:\\a\\ import java._____.File; class A { public static void main( String [] args) { _____f =new _____( "C:\\a\\"); f._____(); } }

import java.io.File; class A { public static void main( String [] args) { File f =new File( "*C:\\a\\b\\*"); f.*mkdir()*; } }

Complete code to check if a file named MyFile.txt exists within the directory C:\a\b import java.io._____; class B { public static void main(String[] args) { File f = new File("_______"); System.out.println(f._____()); } }

import java.io.File; class B { public static void main(String[] args) { File f = new File("*c:\\a\\b\\MyFile.txt*"); System.out.println( *f.exists()*); } }

Complete the following to check if a file exists using only java.nio.file; C:\\a\\b\\log.txt import java.nio.file._____; import java.nio.file._____; import java.nio.file._____; class A { public static void main(String[] args) { _____ p = Paths.get("*C:\\a\\b\\log.txt*"); System.out.println( Files._____(p)); } }

import java.nio.file.*Files*; import java.nio.file.*Path*; import java.nio.file.*Paths*; class A { public static void main(String[] args) { Path p = Paths.get("*C:\\a\\b\\log.txt*"); System.out.println( *Files.exists(p)*); } } Will return true if file exists

Complete the code below that builds the path for a file location. import java.____.file.____; import java.____.file.____; class A { public static void main(String[] args) { Path p1 = _____ ._____ ( "C:\\a\\b\\File.txt"); System. out. println(_____ ); } }

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = *Paths.get*( "C:\\a\\b\\File.txt"); System.out.println(*p1*); } } Note: the file location does not need to exist physically.

A queue is a container that allows elements to be stored and removed

in a first-in-first-out fashion

A stack is a container that allows elements to be stored and removed

in a last-in-first-out fashion

This sorting algorithm begins by sorting the initial portion of the array consisting of 2 elements. Then, the third element is moved to its correct position, relative to the first two elements.

insertion sert

Code to convert a signed byte into an unsigned byte example:

int i = b >= 0 ? b : 256 b;

InputStream is a/an ______

interface

OutputStream is a/an ______

interface

In a linked list, the predecessor of a node X

is undefined if X is the first node, otherwise it is the node whose index is one less than the index of X

Class Scanner

is used extensively to input data from the keyboard. This class can also read data from a file

separator character

is used to separate directories and files in a path.

An ArrayList is so called because

it is implemented as a class that uses an internal array to hold the elements of the list

Java's basic input class is

java.io.InputStream

Java's basic output class is

java.io.OutputStream

The two abstract superclasses that define the basic API for reading and writing characters

java.io.Reader and java.io.Writer

If you are writing an iterator class, it must implement this interface

java.util.Iterator

3 stream intermediate operations for extracting/combining substreams

limit(long n) skip(long n) Stream.concat(Stream<? extends T> s1, Stream<? extends T> s2) p.s. stateful operation limit and skip

This is the number of elements actually stored in a list

list size

other terminal operations aside from collect

long count() void forEach(Consumer<? super T> action) void forEachOrdered(Consumer<? super T> action) Object[] toArray()<A> A[] toArray(IntFunction<A[]> generator) e.g. String[] result = words.toArray(String[]::new);

A binary tree with no root

must be empty

Method that inserts a platform-dependent line-separator string into the output

newLine()

The objects that form the units of memory allocation in a linked lists are called

nodes

FormatterClosedException

occurs if the Formatter is closed when you attempt to output.

NoSuchElementException

occurs if the data being read by a Scanner method is in the wrong format or if there is no more data to input.

FileNotFoundException

occurs if the file does not exist and a new file cannot be created.

Java program

opens a file by creating an object and associating a stream of bytes or characters with it.

Monitor Pattern serializes:

operation on shared objects

Character-based streams

output and input data as a sequence of characters in which every character is two bytes—the number of bytes for a given value depends on the number of characters in that value.

Byte-based streams

output and input data in its binary format—a char is two bytes, an int is four bytes, a double is eight bytes, etc.

Formatter

outputs formatted Strings to the specified stream.

The predecessor of a node in a binary tree is called its

parent

stream intermediate operation that is useful for debugging

peek(Consumer<? super T> action) p.s. stateless operation

The constructor for a ServerSocket takes one parameter, which is the ______

port

The three standard techniques for traversing a binary tree are

preorder, inorder, and postorder

A.java and Log.txt below are located in folder: C:\a What is the the output when code run? import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("C:\\a\\Log.txt"); System. out. println( p1.isAbsolute()); }}

prints true. Paths.get("*C:\\a\\Log.txt*"); is an *absolute path*

Each thread in java has it's own call stack and:

program counter

list( ) method

provided by File object to list down all the files and directories

Class System

provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively.

Files class

provides static methods for common file and directory manipulations, such as copying files; creating and deleting files and directories; getting information about files and directories; reading the contents of files; getting objects that allow you to manipulate the contents of files and directories; and more

Fill in the blank below to get in separator on your particular operating system: public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write(______.________()); bw.write("b"); bw. flush(); bw.close(); }

public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("a"); bw.write( *System.lineSeparator()*); bw.write("b"); bw.flush(); bw.close(); } The above called will *print a* and *b* (on *separate lines*).

A stream of cars going through a toll booth is an example of a

queue

List two methods from BufferedReader

read() - Reads a *single character*. readLine() - Reads a *line of text*.

The two overloaded read() methods that fill a specified array with multiple bytes of data read from the stream:

read(byte[] input) *attempts to fill the specified array input. read(byte[] input, int offset, int length) *attempts to fill the specified subarray of input, starting at offset and continuing for length bytes.

Method that reads a single line of text and returns it as a string

readLine()

To add an element e just after a node referenced by ref, you should use the statement

ref.next = new Node(e, ref.next);

When you create an instance of a generic class, what types can you pass as arguments to the class's type parameter?

reference types only

when you create an instance of a generic class, what types can you pass as arguments to the class's type parameter?

reference types only

serialized object

represented as a sequence of bytes that includes the object's data and its type information.

the stack peek operation

returns the item at the top of the stack, but does not remove it

describe Optional get instance method

returns the wrapped element or NoSuchElementException

A thread class manages a single:

sequential execution

This listiterator method replaces an existing element with a new element

set

Difference between signed byte and unsigned byte:

signed byte values: -128 to 127 unsigned byte values: 0 to 255

Compilers of modern programming languages support method calls and returns with an internal

stack

enumerate stateful vs stateless operations

stateful -distinct() -sorted() / sorted(Comparator<T> c) -skip(long n) -limit(long n) stateless -all other

System.exit

static method terminates an application

Sequential-access files

store records in order by the record-key field.

TelnetInputStream and TelnetOutputStream are undocumented classes hidden inside the:

sun.net package

In a list implementation of a queue, the end of the list at which elements are added is called

the rear of the queue

In a binary tree,

there must be at most one node with no predecessor

If we don't want to use a try/catch block in our method despite the risk of a checked exception being thrown, we can instead use the ______ keyword to pass the responsibility of handling the exception to the caller of our method

throws

If we want to indicate that a method can produce a particular exception type, we need to use the ______ keyword

throws

another version of toMap() for parallel processing

toConcurrentMap(**)

A systematic method that starts at the beginning of the list and processes every node is called

traversal

File FileWriter FileReader BufferedReader BufferedWriter PrintWriter are located in java.io true or false

true

File FileWriter FileReader BufferedReader BufferedWriter PrintWriter need to have be wrapped in a try/catch block or declare that method throws an Exception. true or false

true

Files and Paths contain only static methods. true or false?

true

In File class flush() guarantees last data gets written to disk. close() frees up expensive operating system resources. true or false

true

Path is located in java.nio.file.Path true or false

true

The file "myFile.txt" has two lines containing the following on separate lines: a b When the below code executes "a" and "b" get overwritten resulting in the following on separate lines. c d True or false import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw); pw.println("c"); pw.println("d"); pw.flush(); pw.close(); } }

true

BufferedWriter is more efficient than FileWriter true or false

true. *BufferedWriter* is *more efficient* FileWriter As *FileWriter* writes *single chars* at a time Whereas BufferedWriter *writes chunks* of data to file

Console is located in java.io.Console true or false

true. Console contains methods to access the *PHYSICAL DEVICES* i.e. *keyboard/monitor*

Java 7 Compilers use static methods in Paths to create files and directories.

true. e.g. Path p = Paths.get("C:\\a\\b"); Files.*createDirectories*(p);

In Java 8 we can use a/an _____ to automatically close designated resources when a try/catch block finishes executing

try-with-resources

When accessing resources outside of the managed memory of the JVM, Java requires you to use ______

try/catch blocks

To compare String objects for the purpose of sorting, a programmer should

use the compareTo method of the Comparable interface

File.separator

use to obtain the local computer's proper seperator character rather than explicitly using /or\.

How do you write a byte to an output stream? How do you write multiple bytes to output stream?

write(byte) write(byte[ ])

Look at the following method. public static int Test2(int x, int y) { if ( x < y) { return -5; } else { return (Test2(x - y, y + 5) + 6); } } What is the base case for the method?

x<y

When you create an instance of the JList class,

you pass an array of objects to the constructor

In Java 7, closing a stream is possible with:

"try with resources" The finally clause is no longer needed. Java automatically invokes close() on any AutoCloseable objects declared inside the argument list of the try block. *try with resources can be used with any object that implements the Closeable interface,

List two constructors with parameters of File class

#1 *File(File parent, String child)* - Creates a new File instance from a parent abstract pathname and a child pathname string. #2 *File(String pathname)* - Creates a new File instance by converting the given pathname string into an abstract pathname.

PrintStream

(a subclass of FilterOutputStream) performs text output to the specified stream.

System.in

(standard input stream) object normally inputs bytes from the keyboard

System.err

(the standard error stream object) normally outputs character-based error messages to the screen.

System.out

(the standard output stream object) normally outputs character data to the screen

Console contained a method a returns a string containing whatever the user entered. What is the name of this method?

*readLine()* - Reads a single line of text from the console.

Console input method can be used to not echo password. What is the name of this method?

*readPassword()* - Reads a password or passphrase from the console with *echoing disabled*

three stream objects

- System.in - System.out - System.err

Stream

- a sequence of data - two kinds of Streams = InPutStream, OutPutStream

Creating Directories: 2 useful File utility methods

- mkdir( ) - mkdirs()

Character Streams

- perform input and output for 16-bit unicode - most frequently used classes are, FileReader and FileWriter. - Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

What are the main problems with PrintStream?:

- the output from println() is platform dependent - PrintStream assumes the default encoding of the platform on which it's running - PrintStream eats all exceptions (PrintStream relies on an outdated and inadequate error flag) * PrintWriter still has the problems of platform dependency and minimal error reporting that plague PrintStream

Byte Streams

- used to perform input and output of 8-bit bytes - most frequently used classes are, FileInputStream and FileOutputStream.

All three read() methods return _________ to signal the end of the stream.

-1

reduction or terminal operation

-consumes the stream pipeline. -it does not produce another stream like intermediate operations. -it produces a result or a side-effect.

2. Character Streams

1. All character stream classes are descended from *Reader and Writer*. 2. character stream classes that specialize in file I/O: *FileReader and FileWriter*. The constructors of these class assume that the default character encoding and the default byte-buffer size.

For the File Input Stream, what are some commonly used constructors?

1. File Input Stream (File file) -creates a File input stream by opening a connection to a File object 2. FileInputStream(String pathname) -creates a FileInputStream by opening a connection to a file using its path

How do you create a file output stream object?

1. FileOutputStream(file1) - creates a file output stream to write data to file1 2. FileOutStream(pathname)

NOTE

1. Programs use byte streams to perform input and output of 8-bit bytes 2. All byte stream classes are descended from InputStream and OutputStream abstract classes. 3. all other stream types are built on byte streams. 4. Byte stream classes that specialize in file I/O: FileInputStream and FileOutputStream are concreate samples of Byte steam. We also have many for different purposes. 5. Its always good practice to close opened stream in finally block.

For the File Input Stream, what are some commonly used methods?

1. read() -returns an int which contains the byte value of the byte read 2. close() -all streams must be closed

*Create Buffer Streams*

1. unbuffered stream object is passed to the constructor for a buffered stream class. inp = new BufferedReader(new FileReader("x.txt")); out = new BufferedWriter(new FileWriter("c.txt"));

Three methods to fix race conditions:

1. use thread safe class concurrent.atomic 2. locking or synchronized access 3. thread confinement

Look at the following pseudocode algorithm. algorithm Test14(int x) if (x < 8) return (2 * x) else return (3 * Test14(x - 8) + 8) end Test14 What value is returned for Test14(16)?

32

Default buffer sizes for BufferedOutputStream / BufferedInputStream:

512 bytes for an output stream 2,048 bytes for an input stream

BufferedInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

ByteArrayInputStream

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.

Closeable

A Closeable is a source or destination of data that can be closed.

FileInputStream

A FileInputStream obtains input bytes from a file in a file system.

FilterInputStream

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.

Flushable

A Flushable is a destination of data that can be flushed.

Which receives characters from a Java program and converts these into bytes according to a specified encoding and writes them onto an underlying output stream? A OutputStreamWriter B OutStreamWriter C OutWriter D OutputStreamer

A OutputStreamWriter

PrintStream

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

PushbackInputStream

A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.

SequenceInputStream

A SequenceInputStream represents the logical concatenation of other input streams.

StringReader

A character stream whose source is a string.

PushbackReader

A character-stream reader that allows characters to be pushed back into the stream.

DataInputStream

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

DataOutputStream

A data output stream lets an application write primitive Java data types to an output stream in a portable way.

ObjectStreamField

A description of a Serializable field from a Serializable class.

FileOutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor.

FileFilter

A filter for abstract pathnames.

Which class specifies the API by which characters are read? A java.io.Reader B java.io.Read C java.io.Writer D java.io.Write

A java.io.Reader

If a new element is added to an ArrayList whose internal array if already full,

A new, bigger internal array is created, the elements are moved to the new array, the old internal array is deleted, and then the new element is added

PipedOutputStream

A piped output stream can be connected to a piped input stream to create a communications pipe.

What is serialization?

A process of saving state of a java object to a sequence of bytes. -this sequence of bytes can be sent over a network or stored to a file.

What is a thread?

A separate process in your computer An in

Stream

A stream is a sequence of data items that are conceptually produced one at time. Streams allow manipulate collections of data in declarative way. Stream are "fancy iterators over a collection of data".

new code should use: A. PrintWriter B. PrintStream

A. PrintWriter

InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.

ObjectInputStream

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

File

An abstract representation of file and directory pathnames.

Buffers are not thread-safe. You must employ synchronization when you want to access a buffer from multiple threads.

Are buffers thread safe?

What is the complexity/Difficulty when dealing with threads?

Arises when multiple threads need to access the same resources.

Which is used to take text from the buffer rather than directly from the underlying input stream or other test source? A BufferReader B BufferedReader C BufferRead D BufferedRead

B BufferedReader

Which subclass of InputStream is used to read data from a file? A FileStream B FileInputStream C FileInputOutputStream D FileIOStream

B FileInputStream

functional interface for Boolean??

BooleanSupplier boolean getAsBoolean()

The flush() method

Breaks a deadlock by forcing the buffered stream to send its data even if the buffer isn't yet full. For example, suppose you've written a 300-byte request to an HTTP 1.1 server that uses HTTP Keep-Alive. You generally want to wait for a response before sending any more data. However, if the output stream has a 1,024-byte buffer, the stream may be waiting for more data to arrive before it sends the data out of its buffer. No more data will be written onto the stream until the server response arrives, but the response is never going to arrive because the request hasn't been sent yet!

Classes avaialable to wrap UnBuffered Streams

Buffer Byte Streams: 1. BufferedInputStream 2. BufferedOutputStream Buffered Char Streams: 1. BufferedReader 2. BufferedWriter

We can increase the efficiency of our OutputStreams by using the stream type ______

BufferedOutputStream

The ___________/___________ classes store written data in a buffer (a protected byte array field named buf) until the buffer is full or the stream is flushed

BufferedOutputStream / BufferedInputStream *BufferedInputStream has two constructors, as does BufferedOutputStream:

BufferedReader reads _______ of data to file

BufferedReader reads *CHUNKS* of data to file

BufferedWriter writes _______ of data to file

BufferedWriter writes *CHUNKS* of data to file

What are the two types of stream data?

Byte based/ Character based.

import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get(URI.create( "file:///C://a//File.txt")); System.out.println(p1); } } Consider the above code running on Windows. The above code will give: a) compiler error b) runtime error c) compile and print C:\a\File.txt d) none of the above

C is correct.

setFileSelectionMode

Call method specifies what the user can select from the fileChooser

ObjectInputValidation

Callback interface to allow validation of objects within a graph.

Yes

Can an inner catch re throw an expiation to an outer Catch?

What should you always do before creating a file?

Check to see if it exists. This is a good habit. try{ if(!file.exist()){ create file } }

Java has two kinds of exceptions: ______ Exceptions and Runtime Exceptions

Checked

______ require a user to surround the throwing method invocation with a try/catch block

Checked Exceptions

ObjectInputStream and ObjectOutputStream

Classes (package java.io). which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream

This class provides numerous static methods that perform useful operations on collections

Collections

Sequence of elements

Collections are about data; Streams are about computations

collectors - statistics

Collectors.summarizingInt(ToIntFunction<? super T> mapper) Collectors.summarizingLong(ToLongFunction<? super T> mapper) Collectors.summarizingDouble(ToDoubleFunction<? super T> mapper) double averagingInt|Long|Double(ToInt|Long|DoubleFunction mapper) int|long|double summingXYZ(ToInt|Long|DoubleFunction mapper) e.g. IntSummaryStatistics summary = words.collect(Collectors.summarizingInt(String::length)); void accept(int value) - i/l void accept(long value) - l void accept(double value) - d double getAverage() long getCount(); int|long|double getMax(); int|long|double getMin(); long|double getSum(); void combine(Int|Long|DoubleSummaryStatistics other)

collectors - maps (terminal operation)

Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper) Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper, BinaryOperator<U> mergeFunction) Collectors.toMap(Function<T,R> keyMapper, Function<T,R> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M extends Map> mapSupplier) e.g. Map<Integer, String> personNameMap = persons.collect(Person::getId, Person::getName); Map<Integer, Person> personMap = persons.collect(Person::getId, Function.identity()); Map<Integer, Person> personTreeMap = persons.collect(Person::getId, Function.identity(), TreeMap::new);

basic collectors

Collectors.toSet() Collectors.toList() Collectors.toCollection(Supplier<T> t) Collectors.counting() e.g. Collectors.toCollection(TreeSet::new)

This is an object that can compare two other objects and determine whether one is greater than, less than, or equal to the other

Comparator

Using a for-each loop complete the code below to write out the password to the screen in boolean format. import java.io.Console; class A { public static void main(String[] args) { Console c = System. console(); char[] pw = c. readPassword( "Enter password: "); for(char curChar: _____ ) { c._____ (_____ , _____ ); } }}

Console c = System.console(); char[] pw=c.readPassword( "Enter password: "); for(char curChar: *pw*) { c.*format("%b", curChar)*; } e.g. prompt:> *Java A* prompt:> *Enter Password:* hello prompt:> truetruetruetruetrue

Using a for-each loop complete the code below to write out the password to the screen in string format. import java.io.Console; class A { public static void main(String[] args) { Console c = System.console(); char[] pw = c.readPassword( "Enter password: "); for(char curChar: pw) { c._____ (_____ , curChar); } }}

Console c = System.console(); char[] pw=c.readPassword( "Enter password: "); for(char curChar: pw) { c.*format*(*"%s"*, curChar); } e.g. c:> *Java A* c:> *Enter Password:* hello c:> hello

Console contains methods to access the _____ _____

Console contains methods to access the *PHYSICAL DEVICES* i.e. *keyboard/monitor*

ObjectStreamConstants

Constants written into the Object Serialization Stream.

FileReader

Convenience class for reading character files.

FileWriter

Convenience class for writing character files.

persistent data

Data maintained in files exists beyond the duration of program execution

The ____________/____________ classes provide methods for reading and writing Java's primitive data types and strings in a binary format

DataInputStream and DataOutputStream

readLine()

DataInputStream provides the popular readLine() method that reads a line of text as delimited by a line terminator and returns a string:

What should you know for the test?

Example of deadlock Example of race condition

All exceptions inherit from the ______ class

Exception

What is the difference between printwriter and FileOutputStream?

F.O.S writes to a file as a streams of bytes P.W writes to a file using characters

T/F: Streams are asynchronous

False Streams are synchronous; that is, when a program (really a thread) asks a stream to read or write a piece of data, it waits for the data to be read or written before it does anything else

BufferedWriter is less efficient than FileWriter true or false

False. *BufferedWriter* is *more efficient* than FileWriter As FileWriter writes *single chars* at a time whereas *BufferedWriter* writes *chunks of data to file*

Type out the code used to create a file in Java

File file = new File("fileName"); Creates a file in the directory it was run from

File makes a new _____ file but not the data.

File makes a new *EMPTY* file.

Example

FileInputStream in = new FileInputStream("xanadu.txt"); FileOutputStream out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c);

What class am I? I read characters (single or whole) stream of chars from a file.

FileReader class

FileReader class _____ characters ( _____ or whole) in a _____ of chars from a file.

FileReader class *READ* characters (*SINGLE* or whole) in a *STREAM* of chars from a file.

example of FileReader and FileWriter. *This will read character by character and write it.*

FileReader inputStream = new FileReader("xanadu.txt"); FileWriter outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c)

FileReader reads _______ chars from a _____at a time

FileReader reads *SINGLE* chars from a *FILE* at a time

What class am I? write characters (single or whole) in a stream of chars to a file.

FileWriter class

What is a stream (generally speaking)?

Flow of data Sequence of data and bytes or uni-code characters in some sort of sequential queue.

What does flush() do?

Flushes all the data written to the output stream to the destination. Bytes written to output stream may not have been fully written to storage yet. There is a chance data might be stored in memory somewhere. Calling flush guarantees any buffer data is flushed a.k.a written to the file

The constructor for a Socket takes two parameters, one is the port and the other is the ______

IP Address

We can read data from a file by using a/an ______

InputStream

3 types of Stream Primitive

IntStream LongStream DoubleStream

can you convert from one primitive stream to another

IntStream - asDoubleStream(), asLongStream() LongStream = asDoubleStream() DoubleStream - none mapToInt(XtoYFunction f) mapToLong(XtoYFunction f) mapToDouble(XtoYFunction f)

tagging interface

It does not contain methods

An ArrayList is so called because

It is implemented as a class that uses an internal array to hold the elements of the list

Why you should flush all streams immediately before you close them?

It's important to flush your streams whether you think you need to or not. Depending on how you got hold of a reference to the stream, you may or may not know whether it's buffered. (For instance, System.out is buffered whether you want it to be or not.) Failing to flush when you need to can lead to unpredictable, unrepeatable program hangs that are extremely hard to diagnose if you don't have a good idea of what the problem is in the first place.

What improvement does PrintWriter have over the PrintStream class?

It's internationalizable: PrintWriter offers four write() methods, which write characters rather than bytes; also, if the underlying writer properly handles character set conversion, so do all the methods of the PrintWriter.

FILES_AND_DIRECTORIES

JFileChooser static constant that indicate that files and directories can be selected

This class is a good choice to use when your application will be storing a large amount of data in a list, and a lot of insertions and/or deletions are likely to take place

LinkedList

This list class stores its elements in a data structure that is made of a series of connected nodes

LinkedList

The concrete classes that implement the List interface are

LinkedList, ArrayList, and Vector

NOTE

Most of the classes covered in the I/O Streams section are in the java.io package 1. Byte Streams 2. Character Streams 3. Buffered Streams. 4. Data Streams. 5. Object Streams.

The Java notation MyClass<Student> means that

MyClass is a generic class

If the stack method push is called on an empty stack

None of the above

A Node class for a linked list that can hold elements of type Object can be declared to have fields

Object element; Node next;

The most important concrete subclass of Writer

OutputStreamWriter

Draw an Output stream diagram

PROGRAM ---> OUTPUT STREAM ---> DESTINATION (Dest. could be File, Storage unit) In the output stream there is data that is waiting to be produced into something

PipedReader

Piped character-input streams.

PipedWriter

Piped character-output streams.

Which of the following generic type notations uses a wldcard?

Point<?>

PrintWriter contains extra ______ for _________. Makes it more _____ and ________ than Writer

PrintWriter contains extra *METHODS* for *FORMATTING*. Makes it more *FLEXIBLE* and *POWERFUL* than Writer

PrintWriter

Prints formatted representations of objects to a text-output stream.

This sorting algorithm recursively divides an array into sublists.

Quiksort

What are the two basic functions you can do with a stream?

Read or write.

character based IO

Reader and writer are at the top of the ________class hierarchies.

Java has two kinds of exceptions: Checked Exceptions and ______ Exceptions

Runtime

hasNext

Scanner method determines whether the end-of-file key combination has been entered.

In this sorting algorithm, the smallest value in the array is located and moved to position 0. Then the next smallest value is located and moved to position 1. This process continues until all of the elements have been placed in their proper order

Selection sort

Serializable

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

A/An ______ is used to connect to a remote resource such as a server

Socket

ServerSocket.accept() returns a/an ______

Socket

Class "Outputstream" provides these methods:

Subclasses of OutputStream use these methods to write data onto particular media:

optional methods for producing alternative

T orElse(T other) T orElseGet(Supplier<? extends T> other) <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable

overloaded of reduce()

T reduce(T identity, BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) <U> U reduce( U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) e.g. int result = words.reduce(0, (total, word) -> total + word.length(), (total1, total2) -> total1 + total2);

DataInput

The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types.

DataOutput

The DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream.

InPutStream

The InputStream is used to read data from a source.

Which of the following is true?

The ListIterator interface is a subinterface of the Iterator interface

OutPutStream

The OutputStream is used for writing data to a destination.

StreamTokenizer

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

*NOTE*

The above two I/o are less efficient as each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity. To Overcome this Buffer I/O is implemented in Java.

BufferedOutputStream

The class implements a buffered output stream.

What does the close() method do?

The close() method releases any resources associated with the stream, such as file handles or ports. If the stream derives from a network connection, then closing the stream terminates the connection

A new element is added to an ArrayList object at index k. Assuming the list has size s and does not have to be resized,

The elements at current positions k..s-1 must be moved toward the end of the array

What is de-serialization?

The process of building object state back after reading a sequence of bytes from over a network or from a stored file.

Which of the following is true?

The remove() method of an iterator can only be called after next() has been called

Method to to skip over data without reading it.

The skip() method

writeBytes()

The writeBytes() method iterates through the String argument but writes only the least significant byte of each character. Thus, information will be lost for any string with characters from outside the Latin-1 character set.

writeChars()

The writeChars() method simply iterates through the String argument, writing each character in turn as a two-byte, big-endian Unicode character (a UTF-16 code point, to be absolutely precise).

List one method from FileReader class

There are *no methods* in *FileReader*. However *methods inherited* from: java.lang.*Object* java.io.*InputStreamReader* java.io.*Reader* From java.io.*Reader*: read() - Reads a *single character*

File Navigation and I/O

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O. File Class FileReader Class FileWriter Class

Bridge streams

There are two general-purpose byte-to-character "bridge" streams: *InputStreamReader* and *OutputStreamWriter*. The charset that it uses may be specified by name or may be given explicitly.

ByteArrayOutputStream

This class implements an output stream in which the data is written into a byte array.

LineNumberInputStream Deprecated

This class incorrectly assumes that bytes adequately represent characters.

FilePermission

This class represents access to a file or directory.

Standard Streams : Standard Input

This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.

Why does the Java Collections Framework define a List as an interface rather than a class?

To allow different types of concrete classes, with different performance characteristics to implement the interface

In File class close() method frees up expensive operating system resources

True.

Compilers less than Java 7 uses instance methods on File to create files and directories. True or false

True. e.g. File f = new File("C:\\a\\b\\Log.txt"); f.*createNewFile()*;

15.7.1 Q1: Which of the following statements is false? a. InputStream and OutputStream are abstract classes for performing byte-based I/O. b. Tubes are synchronized communication channels between threads. c. A filter stream provides additional functionality, such as aggregating data bytes into meaningful primitive-type units. FilterInputStream and FilterOutputStream are typically extended, so some of their filtering capabilities are provided by their concrete subclasses. d. A PrintStream performs text output. System.out and System.err are PrintStreams.

Tubes are synchronized communication channels between threads. Actually, pipes are synchronized communication channels between threads.

What is multi-threading?

Two or more tasks executing in a program. Many threads can run concurrently in a program.

If we want to read line by line then.

Use BufferedReader and PrintWriter which can wrap Filereader and Filewriter and has operations Readline and Println.

What code do you need to use if any code is being access by multiple threads?

Use synchronize.

The boolean contains(E element) method searches a ArrayList for a given element. A correct and efficient implementation of this method

Uses sequential search to locate the element

In an application that allows multiple threads to access a list, which concrete list class would you use?

Vector

JDK 1.4 implemented NIO in terms of the following APIs: - Buffers - Channels - Selectors - Regular expressions - Charsets The regular expression and charset APIs were provided to simplify common I/O-related tasks.

What APIs does NIO include?

ByteBuffers (and other primitive-type buffers) created via allocate() or wrap() are nondirect byte buffers. Nondirect byte buffers have backing arrays, and you can access these backing arrays via the array() method (which happens to be declared as byte[] array() in the ByteArray class) as long as hasArray() returns true. (When hasArray() returns true, you'll need to call arrayOffset() to obtain the location of the first data item in the array.)

What are nondirect byte buffers?

Reductions are terminal operations. They reduce the stream to a non-stream value that can be used in your program.

What are reductions?

- available() - mark() - markSupported() - read() - reset() - skip()

What are some methods of InputStream class?

throw an exception

What do try/catch blocks do for a program?

BufferedWriter writes text to a character-output stream (a Writer instance), buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. Invoke either of the following constructors to construct a buffered writer: BufferedWriter(Writer out) BufferedWriter(Writer out, int size) The buffer size may be specified, or the default size (8,192 bytes) may be accepted. The default is large enough for most purposes. BufferedWriter includes a handy void newLine() method for writing a line-separator string, which effectively terminates the current line. BufferedReader reads text from a character-input stream (a Reader instance), buffering characters so as to provide for the efficient reading of characters, arrays, and lines. Invoke either of the following constructors to construct a buffered reader: BufferedReader(Reader in) BufferedReader(Reader in, int size) The buffer size may be specified, or the default size (8,192 bytes) may be used. The default is large enough for most purposes. BufferedReader includes a handy String readLine() method for reading a line of text, not including any line-termination characters.

What does BufferedWriter and BufferedReader do?

FileOutputStream and FileInputStream are useful for writing and reading bytes and arrays of bytes. However, they provide no support for writing and reading primitive-type values (such as integers) and strings. For this reason, Java provides the concrete DataOutputStream and DataInputStream filter stream classes. Each class overcomes this limitation by providing methods to write or read primitive-type values and strings in an operating system-independent way: - Integer values are written and read in big-endian format (the most significant byte comes first) - Floating-point and double precision floating-point values are written and read according to the IEEE 754 standard, which specifies four bytes per floating-point value and eight bytes per double precision floating-point value. - Strings are written and read according to a modified version of UTF-8, a variable-length encoding standard for efficiently storing two-byte Unicode characters.

What does DataOutputStream and DataInputStream do?

Files are common stream destinations and sources. The concrete FileOutputStream class lets you write a stream of bytes to a file; the concrete FileInputStream class lets you read a stream of bytes from a file. FileOutputStream and FileInputStream are useful in a file-copying context.

What does FileOutputStream and FileInputStream do?

FileWriter is a convenience class for writing characters to files. It subclasses OutputStreamWriter, and its constructors, such as FileWriter(String path), call OutputStreamWriter(OutputStream). FileReader is a convenience class for reading characters from files. It subclasses InputStreamReader, and its constructors, such as FileReader(String path), call InputStreamReader(InputStream).

What does FileWriter and FileReader do?

File declares the File[] listRoots() class method to return the root directories (roots) of available file systems as an array of File objects. File[] roots = File.listRoots(); for (File root: roots) System.out.println(root);

What does File[] listRoots() method of the File class do?

Channel is also extended by the java.nio.channels.InterruptibleChannel interface. InterruptibleChannel describes a channel that can be asynchronously closed and interrupted. This interface overrides its Channel superinterface's close() method header, presenting the following additional stipulation to Channel's contract for this method: Any thread currently blocked in an I/O operation on this channel will receive AsynchronousCloseException (an IOException descendent). A channel that implements this interface is asynchronously closeable: When a thread is blocked in an I/O operation on an interruptible channel, another thread may invoke the channel's close() method. This causes the blocked thread to receive a thrown AsynchronousCloseException instance. A channel that implements this interface is also interruptible: When a thread is blocked in an I/O operation on an interruptible channel, another thread may invoke the blocked thread's interrupt() method. Doing this causes the channel to be closed, the blocked thread to receive a thrown ClosedByInterruptException instance, and the blocked thread to have its interrupt status set. (When a thread's interrupt status is already set and it invokes a blocking I/O operation on a channel, the channel is closed and the thread will immediately receive a thrown ClosedByInterruptException instance; its interrupt status will remain set.)

What does InterruptibleChannel interface do?

Threads must often communicate. One approach involves using shared variables. Another approach involves using piped streams via the PipedOutputStream and PipedInputStream classes. The PipedOutputStream class lets a sending thread write a stream of bytes to an instance of the PipedInputStream class, which a receiving thread uses to subsequently read those bytes. Attempting to use a PipedOutputStream object and a PipedInputStream object from a single thread is not recommended because it might deadlock the thread.

What does PipedOutputStream and PipedInputStream do?

Java provides the Writer and Reader classes for performing character I/O. Writer is the superclass of all writer subclasses.

What does Writer and Reader classes do?

InputStream is the superclass of all input stream subclasses.

What does abstract class InputStream do?

OutputStream is the superclass of all output stream subclasses.

What does abstract class OutputStream do?

The count method returns the number of elements of a stream.

What does count method do?

The distinct method returns a stream that yields elements from the original stream, in the same order, except that duplicates are suppressed. Stream<String> uniqueWords = Stream.of("merrily", "merrily", "merrily", "gently").distinct();

What does distinct method do?

Return the absolute form of this File object's abstract path. This method is equivalent to new File(this.getAbsolutePath()).

What does getAbsoluteFile() method of the File class do?

Return the absolute path string of this File object's abstract path. When it's already absolute, the path string is returned as if by calling getPath(). When it's the empty abstract path, the path string of the current user directory (identified via user.dir) is returned. Otherwise, the abstract path is resolved in an operating system-dependent manner. On Unix/Linux operating systems, a relative path is made absolute by resolving it against the current user directory. On Windows operating systems, the path is made absolute by resolving it against the current directory of the drive named by the path, or the current user directory when there is no drive.

What does getAbsolutePath() method of the File class do?

Return the canonical (simplest possible, absolute and unique) form of this File object's abstract path. This method throws java.io.IOException when an I/O error occurs (creating the canonical path may require file system queries); it equates to new File(this.getCanonicalPath()).

What does getCanonicalFile() method of the File class do?

Return the canonical path string of this File object's abstract path. This method first converts this path to the absolute form when necessary, as if by invoking getAbsolutePath(), and then maps it to its unique form in an operating system-dependent way. Doing so typically involves removing redundant names such as "." and ".." from the path, resolving symbolic links (on Unix/Linux operating systems), and converting drive letters to a standard case (on Windows operating systems). This method throws IOException when an I/O error occurs (creating the canonical path may require file system queries).

What does getCanonicalPath() method of the File class do?

returns the number of unallocated bytes in the partition identified by this File object's abstract path; it returns zero when the abstract path doesn't name a partition.

What does getFreeSpace() method of the File class do?

Return the file name or directory name denoted by this File object's abstract path. This name is the last in a path's name sequence. The empty string is returned when the path's name sequence is empty.

What does getName() method of the File class do?

Return the parent path string of this File object's path, or return null when this path doesn't name a parent directory.

What does getParent() method of the File class do?

Convert this File object's abstract path into a path string where the names in the sequence are separated by the character stored in File's separator field. Return the resulting path string.

What does getPath() method of the File class do?

returns the size (in bytes) of the partition identified by this File object's abstract path; it returns zero when the abstract path doesn't name a partition.

What does getTotalSpace() method of the File class do?

returns the number of bytes available to the current JVM on the partition identified by this File object's abstract path; it returns zero when the abstract path doesn't name a partition.

What does getUsableSpace() method of the File class do?

It supports bulk access to file attributes, provides a change notification facility, offers the ability to escape to file system-specific APIs, and has a service provider interface for pluggable file system implementations.

What does improved filesystem interface support?

Return true when this File object's abstract path is absolute; otherwise, return false when it's relative. The definition of absolute path is system dependent. For Unix/Linux operating systems, a path is absolute when its prefix is "/". For Windows operating systems, a path is absolute when its prefix is a drive specifier followed by "\" or when its prefix is "\\".

What does isAbsolute() method of the File class do?

Return true when this File object's abstract path refers to an existing directory.

What does isDirectory() method of the File class do?

Return true when this File object's abstract path refers to an existing normal file. A file is normal when it's not a directory and satisfies other operating system-dependent criteria. It's not a symbolic link or a named pipe, for example. Any nondirectory file created by a Java application is guaranteed to be a normal file.

What does isFile() method of the File class do?

Return true when the file denoted by this File object's abstract path is hidden. The exact definition of hidden is operating system dependent. On Unix/Linux operating systems, a file is hidden when its name begins with a period character. On Windows operating systems, a file is hidden when it has been marked as such in the file system.

What does isHidden() method of the File class do?

Return the time that the file denoted by this File object's abstract path was last modified, or 0 when the file doesn't exist or an I/O error occurred during this method call. The returned value is measured in milliseconds since the Unix epoch (00:00:00 GMT, January 1, 1970).

What does lastModified() method of the File class do?

A convenience method for calling list(), converting its array of Strings to an array of Files, and returning the Files array.

What does listFiles() method of the File class do?

The reduce method is a general mechanism for computing a value from a stream. The simplest form takes a binary function and keeps applying it, starting with the first two elements. List<Integer> values = . . .; Optional<Integer> sum = values.stream().reduce((x, y) -> x + y); In this case, the reduce method computes v0 + v1 + v2 + . . . , where the vi are the stream elements. The method returns an Optional because there is no valid result if the stream is empty. Often, there is an identity value e such that e op x = x, and you can use that element as the start of the computation. For example, 0 is the identity value for addition. Then call the second form of reduce List<Integer> values = . . .; Integer sum = values.stream().reduce(0, (x, y) -> x + y); The identity value is returned if the stream is empty, and you no longer need to deal with the Optional class.

What does reduce method do?

You can concatenate two streams with the static concat method of the Stream class.

What does stream.concat() do?

The call stream.limit(n) returns a new stream that ends after n elements (or when the original stream ends, if it is shorter). This method is particularly useful for cutting infinite streams down to size. Stream<Double> randoms = Stream.generate(Math::random).limit(100);

What does stream.limit(n) do?

the JVM default exception handler terminates execution and displays a stack trace and error message.

What happens if an exception is not caught?

The operating system monitors a collection of streams and returns an indication to the thread of which streams are ready to perform I/O. As a result, a single thread can multiplex many active streams via common code and makes it possible, in a web server context, to manage a huge number of network connections.

What is "readiness selection"?

An instance of the File class contains an abstract representation of a file or directory path (a compact map that locates and identifies a file system object).

What is a File class?

A buffer is an object that stores a fixed amount of data to be sent to or received from an I/O service (an operating system component for performing input/output). It sits between an application and a channel that writes the buffered data to the service or reads the data from the service and deposits it into the buffer.

What is a buffer?

A channel is an object that represents an open connection to a hardware device, a file, a network socket, an application component, or another entity that's capable of performing writes, reads, and other I/O operations. Channels efficiently transfer data between byte buffers and operating system-based I/O service sources or destinations.

What is a channel?

Forcing a CPU to perform I/O tasks and wait for I/O completions (such a CPU is said to be I/O bound) is wasteful of this resource. Performance can be improved by offloading these tasks to DMA controllers so that the processor can get on with other work. A channel serves as a conduit for communicating (via the operating system) with a DMA controller to efficiently drain byte buffers to or fill byte buffers from a disk.

What is a channel?

A stream is an ordered sequence of bytes of arbitrary length.

What is a stream?

Absolute path is a path that starts with the root directory symbol; no other information is required to locate the file/directory that it denotes.

What is an absolute path?

Java provides the DataOutputStream and DataInputStream classes to stream primitive-type values and String objects. However, you cannot use these classes to stream non-String objects. Instead, you must use object serialization and deserialization to stream objects of arbitrary types. Object serialization is a Java virtual machine (JVM) mechanism for serializing object state into a stream of bytes. Its deserialization counterpart is a JVM mechanism for deserializing this state from a byte stream. Note An object's state consists of instance fields that store primitive-type values and/or references to other objects. When an object is serialized, the objects that are part of this state are also serialized (unless you prevent them from being serialized). Furthermore, the objects that are part of those objects' states are serialized (unless you prevent this), and so on. Java supports default serialization and deserialization, custom serialization and deserialization, and externalization.

What is object serialization and deserialization?

b

What is the output of this program? class output { public static void main(String args[]) { StringBuffer c = new StringBuffer("Hello"); System.out.println(c.length()); } } a) 4 b) 5 c) 6 d) 7

b

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello"); StringBuffer s2 = s1.reverse(); System.out.println(s2); } } a) Hello b) olleH c) HelloolleH d) olleHHello

c

What is the output of this program? class output { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Hello"); s1.setCharAt(1,x); System.out.println(s1); } } a) xello b) xxxxx c) Hxllo d) Hexlo

InputStream subclasses such as ByteArrayInputStream support marking the current read position in the input stream via the mark() method and later return to that position via the reset() method.

What subclass of InputStream does support mark() and reset() methods?

ByteArrayOutputStream and ByteArrayInputStream are useful when you need to convert an image to an array of bytes, process these bytes in some manner, and convert the bytes back to the image.

When are ByteArrayOutputStream and ByteArrayInputStream useful?

a

Which exception is thrown by read() method? a) IOException b) InterruptedException c) SystemException d) SystemInputException

a

Which of the following statement is correct? a) reverse() method reverses all characters. b) reverseall() method reverses all characters. c) replace() method replaces first occurrence of a character in invoking string with another character. d) replace() method replaces last occurrence of a character in invoking string with another character.

byte streams are useful for binary IO and character streams are optimized for Unicode.

Why does java define both byte and character streams?

Random access can speed up searching and sorting capabilities.

Why to use random access?

What is wrapping-chaining with an example from classes File FileWriter and PrintWriter in java.io?

Wrapping-chaining class is where one *object* is *passed* as a *parameter* to another. In the context of *Java I/O* e.g. *File f = new File("C:\\a\\myFile.txt");* FileWriter fw = new FileWriter(*f*); *PrintWriter pw = new PrintWriter(fw);* *pw*.println("c"); Where *FileWriter* is *wrapped* inside *PrintWriter*

BufferedWriter

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

built-in (primitive only) operation

XYZSummaryStatistics summaryStatistics() OptionalDouble average() int|long|double sum() OptionalInt|Long|Double min() OptionalInt|Long|Double max()

File object

You use _________ to create directories, to list down files available in a directory.

What is the output of this program if input given is "abc'def/'egh"? class Input_Output { public static void main(String args[]) throws IOException { char c; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { c = (char) obj.read(); System.out.print(c); } while(c != '\''); } } a) abc' b) abcdef/' c) abc'def/'egh d) abcqfghq

a

Which exception is thrown by read() method? a) IOException b) InterruptedException c) SystemException d) SystemInputException

a

Which of these class is implemented by FilterInputStream class? a) InputStream b) InputOutputStream c) BufferedInputStream d) SequenceInputStream

a

Which of these class is used to read characters and strings in Java from console? a) BufferedReader b) StringReader c) BufferedStreamReader d) InputStreamReader

a

Which of these classes are used by Byte streams for input and output operation? a) InputStream b) InputOutputStream c) Reader d) All of the mentioned

a

Which of these method of class StringBuffer is used to reverse sequence of characters? a) reverse() b) reverseall() c) Reverse() d) reverseAll()

a

A directory

a File which can contain a list of other files and directories.

If the autoFlush argument is true, the stream will be flushed every time these events occur:

a byte array or linefeed is written or a println() method is invoked

end-of-file marker

a count of the total bytes in the file that is recorded in a system-maintained administrative data structure

In a typical circular doubly linked list, a node has

a field to store the element, and two references to keep track of successor and predecessor nodes

import java.nio.file.Path; import java.nio.file.Paths; class A { public static void main(String[] args) { Path p1 = Paths.get("C:\\a\\b\\File.txt"); System.out.println(p1); } } File location does not exist physically in memory. The above code will give: a) compiler error b) runtime error c) compile and print "C:\\a\\b\\File.txt" d) none of the above

a is correct. The *folders* and *subfolders do not* need to *exist* physically in order for this to combine.

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileReader fr =new FileReader(f); BufferedReader br = new BufferedReader(fr); System.out.println(br.readLine()); br.flush(); br.close();} } Considering "hello world" is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

a is correct. *BufferedReader* class *does not* have a *flush()* method. If the *flush()* method was *removed* then it would *print "hello"* to the screen. Note: *flush()* is located in *BufferedWriter*.

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); BufferedReader br = new BufferedReader(f); System.out.println(br.readLine()); br.close();} } Considering "hello world" is in file myFile.txt (where "hello" is on the first line and "world" on the second) The above code will give: a) compiler error b) runtime error c) compile and print "hello" d) none of the above

a is correct. import java.io.BufferedReader; import java.io.File; import java.io.FileReader; class A { public static void main(String[] args) throws Exception { *File f* = new File("C:\\a\\myFile.txt"); br* = new BufferedReader(*f*); System.out.println(br.readLine()); br.close();} } *BufferedReader* doesn't take File as a param. Solution: *File* object f needs to be *wrapped* in *FileReader* fr object which needs to be *wrapped* in *BufferedReader* br object in order to compile i.e. *File* wrapped in *FileReader* wrapped in *BufferedReader* e.g. File *f* = new File("C:\\a\\ myFile.txt"); FileReader *fr* = new FileReader(*f*); BufferedReader br = new BufferedReader(*fr*);

An AVL tree is

a kind of binary search tree

A list in which each stored element is associated with a reference to its successor is called

a linked list

If one thread tries to read the data and other thread tries to update the same data, it leads to an inconsistent state. Depending on the order in which the data were accessed, corrupted objects can result. This situation is often referred to as:

a race condition

Thread safety means that the fields of an object or class always maintain:

a valid state

2 ideal usages of optional

a) consumes the correct value b) produces an alternative

A serialized object is ________. a. an object represented as a sequence of bytes used to store the object's data in a file b. an object in memory that has been recreated from data in a file c. a standard output stream object used to convert objects in code to data in a file d. None of the above.

a. An object represented as a sequence of bytes used to store the object's data in a file.

15.7.2 Q1: The ________ abstract classes are Unicode character-based streams. a. Reader and Writer b. BufferedReader and BufferedWriter c. CharArrayReader and CharArrayWriter d. UnicodeReader and UnicodeWriter

a. Reader and Writer

The ________ abstract classes are Unicode character-based streams. a. Reader and Writer b. BufferedReader and BufferedWriter c. CharArrayReader and CharArrayWriter d. UnicodeReader and UnicodeWriter

a. Reader and Writer

15.5 Q2: A serialized object is ________. a. an object represented as a sequence of bytes used to store the object's data in a file b. an object in memory that has been recreated from data in a file c. a standard output stream object used to convert objects in code to data in a file d. None of the above.

a. an object represented as a sequence of bytes used to store the object's data in a file.

Which JFileChooser method returns the file the user selected? a. getSelectedFile. b. getFile. c. getOpenDialog. d. showOpenDialog.

a. getSelectedFile

15.6 Q2: Which JFileChooser method returns the file the user selected? a. getSelectedFile. b. getFile. c. getOpenDialog. d. showOpenDialog.

a. getSelectedFile.

Which JFileChooser method specifies what users can select in the dialog? a. setFileSelectionMode b. setSelectionMode c. showOpenDialog d. None of the above.

a. setFileSelectionMode

15.6 Q1: Which JFileChooser method specifies what users can select in the dialog? a. setFileSelectionMode b. setSelectionMode c. showOpenDialog d. None of the above

a. setFileSelectionMode.

The read() method is declared ____________ because subclasses need to change it to handle their particular medium

abstract

ServerSocket.______() is an example of a blocking call

accept

To add a new value to a heap you should

add it as a leaf and then sift up

The stack push operation

adds a single item to the stack

In a complete binary tree

all of the above

The HeapSort method

all of the above

Pipes

are synchronized communication channels between threads

Which of these class is used to create an object whose character sequence is mutable? a) String() b) StringBuffer() c) Both of the mentioned d) None of the mentioned

b

Which of these classes are used by character streams for input and output operations? a) InputStream b) Writer c) ReadStream d) InputOutputStream

b

: Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter a. A and B. b. C and D. c. C, D, E, F. d. E and F.

b. C and D

Files static method ________ receives a Path and returns a boolean indicating whether that Path represents a directory on disk. a. isDiskDirectory b. isDirectory c. isFileDirectory d. isPath

b. IsDirectory

15.7.1 Q3: Which of the following statements is false? a. With a BufferedOutputStream each output operation is directed to a buffer large enough to hold the data of many output operations. Transfer to the output device is performed in one large physical output operation when the buffer fills. b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method. c. With a BufferedInputStream, many "logical" chunks of data from a file are read as one large physical input operation into a memory buffer. d. With a BufferedInputStream, as a program requests data, it's taken from the buffer. When the buffer is empty, the next actual physical input operation is performed.

b. With a BufferedOutputStream, a partially filled buffer can be forced out to the device at any time by invoking the stream object's force method. Actually, it's the flush method

15.2 Q3: Streams that input bytes from and output bytes to files are known as ________. a. bit-based streams b. byte-based streams c. character-based streams d. Unicode-based streams

b. byte-based streams

Streams that input bytes from and output bytes to files are known as ________. a. bit-based streams b. byte-based streams c. character-based streams d. Unicode-based streams

b. byte-based streams

15.3 Q6: Files static method ________ receives a Path and returns a boolean indicating whether that Path represents a directory on disk. a. isDiskDirectory b. isDirectory c. isFileDirectory d. isPath

b. isDirectory

Which of the following statements is false? a. A Path represents the location of a file or directory. b. Path objects open files and provide file-processing capabilities. c. Class Paths is used to get a Path object representing a file or directory location. d. The static method get of class Paths converts a String representing a file's or directory's location into a Path object.

b. path objects open files and provide file-processing capabilities.

15.4.4 Q1: Records in a sequential file are not usually updated in place. Instead ________. a. the updated data is placed in a "surrogate" file b. the entire file is usually rewritten c. the file is truncated d. The above statement is false—records in sequential files are usually updated in place.

b. the entire file is usually rewritten

Records in a sequential file are not usually updated in place. Instead ________. a. the updated data is placed in a "surrogate" file b. the entire file is usually rewritten c. the file is truncated d. The above statement is false—records in sequential files are usually updated in place

b. the entire file is usually rewritten

Adding the services of one stream to another is known as ________. a. chaining b. wrapping c. adding d. sequencing

b. wrapping

15.5 Q3: Adding the services of one stream to another is known as ________. a. chaining b. wrapping c. adding d. sequencing

b. wrapping.

In a generic method, a type parameter is defined __________.

before the methods return type

in a generic method, a type parameter is defined

before the methods return type

This search algorithm repeatedly divides the portion of an array being searched in half.

binary search

This search algorithm requires that the array's contents be sorted.

binary search

ServerSocket.accept is an example of a/an ______

blocking call

boolean reduction operations

boolean allMatch(Predicate<? super T> predicate) - returns true if empty stream boolean anyMatch(Predicate<? super T> predicate) - retruns false if empty stream boolean noneMatch(Predicate<? super T> predicate) - returns true if empty stream **short-circuit terminal operations

other operations of Optional (similar to Stream)

boolean filter(Predicate<? super T> predicate) <U> Optional<U> map(Function<? super T, ? extends U> mapper) <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper) **flatMap - for chaining multiple map optional e.g. Double result = Optional.of (-4.0).flatMap(Test::inverse).flatMap(Test::squareRoot)

optional methods for consuming values

boolean isPresent() void ifPresent(Consumer<? super T> consumer)

convert primitive stream to Stream

boxed() mapToObj(IntFunction<? extends U> mapper) mapToObj(LongFunction<? extends U> mapper) mapToObj(DoubleFunction<? extends U> mapper)

File a = new File("c:\\a"); File f = new File(a,"f.txt"); System.out.println( f.createNewFile()); System.out.println(f.exists()); The folder and file does not exist. The above code will give: a) compiler error b) runtime error c) Compile and Print "true true" d) None of the above

c is correct. f.*createNewFile() creates* "f.txt" and prints '*true*' f.*exists()* prints *true*. Note: If folder and *file exist already* then: f.*createNewFile() prints *false* and f.*exists()* prints *true*

Which of the following statements is false? a. A DirectoryStream enables a program to iterate through the contents of a directory. b. Character-based input and output can be performed with classes Scanner and Formatter. c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory. d. Every file or directory on a disk drive has the same root directory in its path.

c. A relative path contains all the directories, starting with the root directory, that lead to a specific file or directory.

Which of the following statements is true? a. Class Scanner provides the ability to reposition to the beginning of a file with method seek. b. Class Scanner provides the ability to reposition to the beginning of a file with method reposition. c. Class Scanner does not provide the ability to reposition to the beginning of the file. d. If it is necessary to read a sequential file again, the program can simply keep reading—when the end of the file is reached, the Scanner is automatically set to point back to the beginning of the file.

c. Class scanner does not provide the ability to reposition to the beginning of the file.

15.3 Q2: Class ________ provides static methods for common file and directory manipulations, including methods for copying files; creating and deleting files and directories; getting information about files and directories; reading the contents of files; getting objects that allow you to manipulate the contents of files and directories; and more. a. File b. FileAndDirectory c. Files d. FilesAndDirectories

c. Files

Class ________ provides static methods for common file and directory manipulations, including methods for copying files; creating and deleting files and directories; getting information about files and directories; reading the contents of files; getting objects that allow you to manipulate the contents of files and directories; and more. a. File b. FileAndDirectory c. Files d. FilesAndDirectories

c. Files

15.4.2 Q1: What does the following statement do? Scanner scanner = new Scanner(Paths.get("test.txt")); a. Opens a binary file for input. b. Opens a binary file for output. c. Opens a text file for input. d. Opens a text file for output.

c. Opens a text file for input.

: What interface must a class implement to indicate that objects of the class can be output and input as a stream of bytes? a. Synchronize b. Deserializable c. Serializable d. ObjectOutput

c. Serializable

15.5.1 Q1: What interface must a class implement to indicate that objects of the class can be output and input as a stream of bytes? a. Synchronize b. Deserializable c. Serializable d. ObjectOutput

c. Serializable.

How do methods setIn, setOut and setErr affect the standard input, output and error streams? a. They output data to the standard input, output and error streams. b. They provide the only way to access the standard input, output and error streams. c. They redirect the standard input, output and error streams. d. They empty the standard input, output and error streams.

c. The redirect the standard input, output, and error streams.

15.2 Q2: How do methods setIn, setOut and setErr affect the standard input, output and error streams? a. They output data to the standard input, output and error streams. b. They provide the only way to access the standard input, output and error streams. c. They redirect the standard input, output and error streams. d. They empty the standard input, output and error streams.

c. They redirect the standard input, output and error streams.

What does the following statement do? Scanner scanner = new Scanner(Paths.get("test.txt")); a. Opens a binary file for input. b. Opens a binary file for output. c. Opens a text file for input. d. Opens a text file for output.

c. opens a text file for input.

InputStream object 's helper methods

can be used to read to stream or to do other operations on the stream. - public void close() throws IOException{} - protected void finalize()throws IOException {} - public int read(int r)throws IOException{} - public int read(byte[] r) throws IOException{} - public int available() throws IOException{}

A generic class

can extend generic and non-generic classes

In general, adding an element e in one step to a singly-linked list just before a node referenced by ref

can only be done when ref is the last node in the list

If we want to log or recover from an error in our application, we should use a/an ______

catch block

the stack empty operation

checks to see if there is at least one item on the stack

Always ______ your streams

close

The ______ method will automatically flush a stream

close

Finally, when you're done with a stream, close it by invoking this method - it releases any resources associated with the stream, such as file handles or ports.

close() method

absolute path

contains all directories, starting with the root directory, that lead to a specific file or directory.

What is the output of this program if input given is "Hello stop World"? class Input_Output { public static void main(String args[]) throws IOException { string str; BufferedReader obj = new BufferedReader(new InputStreamReader(System.in)); do { str = (char) obj.readLine(); System.out.print(str); } while(!str.equals("strong")); } } a) Hello b) Hello stop c) World d) Hello stop World

d

Which of the following statements is false? a. Path method isAbsolute returns a boolean indicating whether a Path represents an absolute path to a file or directory. b. Files static method getLastModifiedTime receives a Path and returns a FileTime (package java.nio.file.attribute) indicating when the file was last modified. c. Files static method size receives a Path and returns a long representing the number of bytes in the file or directory. For directories, the value returned is platform specific. d. All of the above are true.

d. All of the above are true

When using an ObjectInputStream to read data from a file, what happens when an end-of-file marker is reached? a. Nothing occurs. b. An end-of-file character is read by the program. c. Method readObject returns the value 0. d. An EOFException is thrown.

d. An EOFException is thrown

15.5.2 Q1: When using an ObjectInputStream to read data from a file, what happens when an end-of-file marker is reached? a. Nothing occurs. b. An end-of-file character is read by the program. c. Method readObject returns the value 0. d. An EOFException is thrown.

d. An EOFException is thrown.

15.7.1 Q2: ________ is an I/O-performance-enhancement technique—it reduces the number of I/O operations by combining smaller outputs together in memory; the number of physical I/O operations is much smaller than the number of I/O requests issued by the program. a. Aggregating b. Accumulating c. Amassing d. Buffering

d. Buffering.

Which of the following statements is false? a. A LineNumberReader is a buffered character stream that tracks the number of lines read. b. Classes FileReader and FileWriter perform character-based file I/O. c. Class PipedReader and class PipedWriter implement piped-character streams for transferring data between threads. d. Class StringReader and StringWriter read characters from and write characters to Streams, respectively.

d. Class StringReader and StringWriter read characters from and write characters to Streams respectively.

Which of the following statements is false? a. Storage of data variables and arrays is temporary. b. Data is lost when a local variable "goes out of scope." c. Files are used for long-term retention of large amounts of data. d. Data maintained in files is often called transient data.

d. Data maintained in files is often called transient data

Which statement regarding Java files is false? a. Java imposes no structure on a file. b. Notions like "record" do not exist in Java files. c. The programmer must structure files to meet the requirements of applications. d. Records in a Java sequential file are stored in order by record key.

d. Records in a java file are stored in order by record key.

15.3 Q5: Path method ________ returns the String name of a file or directory without any location information. a. getStringName b. getFileOrDirectoryName c. getDirectoryName d. getFileName

d. getFileName

Path method ________ returns the String name of a file or directory without any location information. a. getStringName b. getFileOrDirectoryName c. getDirectoryName d. getFileName

d. getFileName

GZIPInputStream

decompresses data

CipherInputStream

decrypts data

DataInput

describes methods for reading primitive types from an input stream.

Class JFileChooser

displays a dialog that enables the user to easily select files or directories.

stream intermediate operation that are stateful

distinct() sorted() sorted(Comparator<? super T> comparator) **all stateful

Invoking the constructor for the File object ______ create an actual file on the file system

does not

The method run() in the generic thread class by default:

doesn't do anything

Threads can be created and deleted ______.

dynamically

Class Formatter

enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.

the process used by the Java compiler to remove generic notation and substitute an actual type for type parameters is known as

erasure

logic error

error made when using \ as a directory sparator rather than \\ in a string literal

In a binary tree that is a heap

every non root node must have a value greater than that of its parent

A thread is an:

execution stream within a process

File FileWriter FileReader BufferedReader BufferedWriter PrintWriter do not need to have be wrapped in a try/catch block or declare that method throws an Exception. true or false

false *Must* be *wrapped* in a *try/catch* block or declare that method *throws* an *Exception*.

Path is located in java.io.file.Path. True or false?

false it is located in: java.*nio*.file.Path

File FileWriter FileReader BufferedReader BufferedWriter PrintWriter are located in java.lang true or false

false located in *java.io*

Path and Paths contain only static methods. true or false?

false. *Path* is an *interface.*

A file "myFile.txt" has two lines containing the following chars on separate lines: a b When the below code executes c and d get appended to the file resulting in the following chars each on separate lines: a b c d True or false? import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; class A { public static void main(String[] args) throws Exception { File f = new File("C:\\a\\myFile.txt"); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter( fw); pw.println("c"); pw.println("d"); pw.flush(); pw.close(); } }

false. *a* *b* get *overwritten* with *c* and *d* therefore *output* would be: *c* *d*


Related study sets

Study.com Historical Methods Ch 4

View Set

Chapter 61: Management of Patients with Neurologic Dysfunction - ML3

View Set

Chapter 5 Short-Term and Working Memory

View Set

Ch 16 small business protection: risk management and insurance

View Set