Java Reference
In-Depth Information
Self-Test Exercises
32. Write code to open the binary file named someStuff and connect it to an
ObjectInputStream object named inputThing so it is ready for reading.
33. Give a statement that will read a number of type double from the file someStuff
and place the value in a variable named number . Use the stream inputThing that
you created in Self-Test Exercise 32. (Assume the first thing written to the file
was written using the method writeDouble of the class ObjectOutputStream and
assume number is of type double .)
34. Give a statement that will close the stream inputThing created in Self-Test
Exercise 32.
35. Can one program write a number to a file using writeInt and then have another
program read that number using readLong ? Can a program read that number
using readDouble ?
36. Can you use readUTF to read a string from a text file?
Display 10.16 Reading from a Binary File (part 1 of 2)
1
import java.io.ObjectInputStream;
2
import java.io.FileInputStream;
3
import java.io.IOException;
4
import java.io.FileNotFoundException;
5 public class BinaryInputDemo
6{
7 public static void main(String[] args)
8 {
9
try
10
{
11
ObjectInputStream inputStream =
12
new ObjectInputStream( new FileInputStream("numbers.dat"));
13
System.out.println("Reading the file numbers.dat.");
14
int n1 = inputStream.readInt();
15
int n2 = inputStream.readInt();
16
System.out.println("Numbers read from file:");
17
System.out.println(n1);
18
System.out.println(n2);
19
inputStream.close();
20
}
Search WWH ::




Custom Search