Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

Find the error in each block of code and show how to correct it. a) Assume that account, company and amount are declared. Object0utputStream outputStream; outputStream.writeInt( account ); outputStream.writeChars( company ); outputStream.writeDouble ( amount ); b) The following statements should read a record from the file "payables.txt". The Scanner variable inPayable should be used to refer to this file. Scanner inPayable = new Scanner( new File( "payables.txt" ) ); PayablesRecord record = ( PayablesRecord ) inPayable.readobject();

Short Answer

Expert verified
Initialize `ObjectOutputStream` correctly and use `ObjectInputStream` for reading objects.

Step by step solution

01

Identify the Error in Code Block (a)

In code block (a), the error is that the `ObjectOutputStream` object `outputStream` is not initialized before it is used. The stream must be associated with an underlying byte stream, such as a `FileOutputStream`.
02

Correct Code Block (a)

To correct the code, initialize the `ObjectOutputStream` with a `FileOutputStream`. For example: ```java outputStream = new ObjectOutputStream(new FileOutputStream("output.dat")); outputStream.writeInt(account); outputStream.writeChars(company); outputStream.writeDouble(amount); ``` This will attach the object output stream to a file named "output.dat".
03

Identify the Error in Code Block (b)

In code block (b), the error is that the `Scanner` class does not have a `readObject()` method. This method is used for object input streams, not scanners.
04

Correct Code Block (b)

To correct this, replace the `Scanner` with an `ObjectInputStream`, which does support `readObject()`. Here is the corrected code: ```java ObjectInputStream inPayable = new ObjectInputStream(new FileInputStream("payables.txt")); PayablesRecord record = (PayablesRecord) inPayable.readObject(); ``` Ensure that the required class imports are included, and handle exceptions such as `ClassNotFoundException` and `IOException`.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

ObjectOutputStream
In Java Input/Output operations, `ObjectOutputStream` plays a crucial role in serializing objects. Serialization makes it possible to write an object to a file, so it can be reconstructed later.
For the `ObjectOutputStream` to work, it needs to be initialized properly.
  • Always connect it with a `FileOutputStream` to specify the file destination.
  • Use the `writeObject()` method to save objects, but `writeInt()` or `writeChars()` can also be used for primitives and strings.
  • Remember to close your stream with `close()` method to release system resources.
This stream makes it easy to transfer objects into files, making it incredibly useful for preserving object states between program runs.
FileOutputStream
`FileOutputStream` is a byte stream class used in Java for writing streams of raw bytes to a file. This stream is particularly useful for writing binary data.
Connecting `FileOutputStream` with an `ObjectOutputStream` allows serialization of objects to a file. Here are some critical features:
  • It directs the bytes to a specified file, for example, "output.dat".
  • Using `write()` method, you can write data as bytes directly into the file.
  • Always handle exceptions like `IOException` to manage file access issues safely.
In essence, `FileOutputStream` is like the road that guides data bytes from your program to an external file.
ObjectInputStream
`ObjectInputStream` is the counterpart to `ObjectOutputStream`, enabling the reading and deserialization of objects that have been written to an output stream. When you want to access the previously stored data, this class comes into play.
  • You must link it with a `FileInputStream` to specify the input source file.
  • The `readObject()` method reads bytes and converts them back into the original object form.
  • Make sure to handle exceptions like `IOException` and `ClassNotFoundException` which occur during deserialization.
In Java, `ObjectInputStream` makes retrieving data stored as objects a seamless process, simplifying data restoration and usage.
Java I/O streams
Java I/O (Input/Output) streams serve as a powerful abstraction for reading from and writing to byte and character streams. These streams simplify data processing by handling I/O through mechanisms like files, network sockets, or byte arrays.
Some key points about Java I/O streams include:
  • Character Streams deal with reading/writing of character-based data, while Byte Streams handle binary data.
  • Using `BufferedReader` or `BufferedOutputStream` can increase efficiency by buffering data.
  • Java streams use various mechanisms like `try-with-resources` to enforce automatic resource management and exception handling.
Java's I/O streams systematically manage data flow, freeing developers to focus more on application logic and less on intricate details.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

(Telephone-Number Word Generator) Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them (Fig. 14.27 ). Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is \(686-2377\) might use the correspondence indicated in Fig. 14.27 to develop the seven-letter word "NUMBERS." Every seven-letter word corresponds to exactly one seven-digit telephone number. A restaurant wishing to increase its takeout business could surely do so with the number \(825-3688\) (i.e., "TAKEOUT"). Every seven-letter phone number corresponds to many different seven-letter words. Unfortunately, most of these words represent unrecognizable juxtapositions of letters. It is possible, however, that the owner of a barbershop would be pleased to know that the shop's telephone number, \(424-7288,\) corresponds to "HAIRCUT." The owner of a liquor store would, no doubt, be delighted to find that the store's number, \(233-7226,\) corresponds to "BEERCAN." A veterinarian with the phone number \(738-2273\) would be pleased to know that the number corresponds to the letters "PETCARE." An automotive dealership would be pleased to know that the dealership number, \(639-2277,\) corresponds to "NEWCARS." Write a program that, given a seven-digit number, uses a Printstream object to write to a file every possible seven-letter word combination corresponding to that number. There are \(2,187\left(3^{7}\right)\) such combinations. Avoid phone numbers with the digits 0 and 1

Fill in the blanks in each of the following statements: a) Ultimately, all data items processed by a computer are reduced to combinations of ________ and _________ b) The smallest data item a computer can process is called a(n) ____________ c) \(A(n)\) ___________ can sometimes be viewed as a group of related records. d) Digits, letters and special symbols are referred to as _________ e) A database is a group of related ___________ f) Object _____________ normally enables a program to output error messages to the screen.

Determine which of the following statements are true and which are false. If \(f a l\) se, explain why. a) The programmer must explicitly create the stream objects System. in, System. out and System .err. b) When reading data from a file using class Scanner, if the programmer wishes to read data in the file multiple times, the file must be closed and reopened to read from the beginning of the file. This moves the file-position pointer back to the beginning of the file. c) Method exists of class File returns true if the name specified as the argument to the File constructor is a file or directory in the specified path. d) Binary files are human readable. e) An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. f) Class Formatter contains method printf, which enables formatted data to be output to the screen or to a file.

Complete the following tasks, assuming that each applies to the same program: a) Write a statement that opens file "oldmast.ser" for input-use objectInputstream variable in01dMaster to wrap a FileInputStream object. b) Write a statement that opens file "trans.ser" for input-use ObjectInputStream variable inTransaction to wrap a FileInputStream object. c) Write a statement that opens file "newmast.ser" for output (and creation)-use \(0 \mathrm{b}-\) ject0utputStream variable outNewMaster to wrap a File0utputStream. d) Write a statement that reads a record from the file "oldmast.ser". The record is an object of class AccountRecordSerializable- use ObjectInputStream variable in01dMaster. Assume class AccountRecordSerializable is the same as the AccountRecordSerializable class in Fig. 14.17 e) Write a statement that reads a record from the file "trans.ser". The record is an object of class TransactionRecord - use ObjectInputStream variable inTransaction. f) Write a statement that outputs a record to the file "newmast.ser". The record is an object of type AccountRecordSerializable-use Object0utputStream variable outNewMaster.

Fill in the blanks in each of the following statements: a) Computers store large amounts of data on secondary storage devices as __________ b) \(A(n)\) ____________ is composed of several fields. c) To facilitate the retrieval of specific records from a file, one field in each record is chosen as a \((n)\) ____________ d) Files that are created using byte-based streams are referred to as _________ files, while files created using character-based streams are referred to as ___________ files. e) The standard stream objects are __________, _________ and ____________

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free