SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
File Io
Exercise:
Programming Projects
Question:8 | ISBN:9780132830317 | Edition: 5

Question

Write a program that will search a binary file of numbers of type int and write the largest and the smallest numbers to the screen. The file contains nothing but numbers of type int written to the file with writeInt.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestDemo {
	public static void main(String args[]) 
	{
		try 
		{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("writeIntFile.dat"));
			System.out.println("Ten Random integer numbers are: ");
			for (int i = 0; i < 10; i++)
			{
				int number = (int)(Math.random() * 20) + 1;
				System.out.println(" " + number);
				os.writeInt(number);
			}
			os.close();
	ObjectInputStream is = new ObjectInputStream(new FileInputStream("writeIntFile.dat"));

			int small = 20, large = 0;
			try
			{
				while(true)
				{
					int nextInt = is.readInt();
					if(nextInt < small)
						small = nextInt;
					if(nextInt > large)
						large = nextInt;
				}
			}
			catch (IOException e)
			{
				System.out.println("\nLargest number: " + large);
				System.out.println("Smallest number: " + small);
			}
		}	
		catch(IOException e)
		{
			System.out.println("Error with file output.");
		}
	}
}

OUTPUT:

Ten Random integer numbers are: 
 12
 7
 20
 11
 6
 5
 20
 16
 20
 18

Largest number: 20
Smallest number: 5

 

0 0

Discussions

Post the discussion to improve the above solution.