Java Reference
In-Depth Information
The following statements create data streams. The first statement creates an input stream for
the file in.dat ; the second statement creates an output stream for the file out.dat .
DataInputStream input =
( new FileInputStream( "in.dat" ));
DataOutputStream output =
( new FileOutputStream( "out.dat" ));
new DataInputStream
new DataOutputStream
Listing 19.2 writes student names and scores to a file named temp.dat and reads the data back
from the file.
L ISTING 19.2 TestDataStream.java
1 import java.io.*;
2
3 public class TestDataStream {
4
public static void main(String[] args) throws IOException {
5
// Create an output stream for file temp.dat
6
7
8
9
DataOutputStream output =
output stream
new DataOutputStream( new FileOutputStream( "temp.dat" ));
// Write student test scores to the file
10
11
12 output.writeUTF( "Susan" );
13 output.writeDouble( 185.5 );
14 output.writeUTF( "Kim" );
15 output.writeDouble( 105.25 );
16
17 // Close output stream
18 output.close();
19
20
output.writeUTF( "John" );
output
output.writeDouble( 85.5 );
close stream
// Create an input stream for file temp.dat
DataInputStream input =
21
22
23
24 // Read student test scores from the file
25 System.out.println( + " " + );
26 System.out.println(input.readUTF() + " " + input.readDouble());
27 System.out.println(input.readUTF() + " " + input.readDouble());
28 }
29 }
input stream
new DataInputStream( new FileInputStream( "temp.dat" ));
input.readUTF()
input.readDouble()
input
John 85.5
Susan 185.5
Kim 105.25
A DataOutputStream is created for file temp.dat in lines 6-7. Student names and scores
are written to the file in lines 10-15. Line 18 closes the output stream. A DataInputStream
is created for the same file in lines 21-22. Student names and scores are read back from the
file and displayed on the console in lines 25-27.
DataInputStream and DataOutputStream read and write Java primitive type values
and strings in a machine-independent fashion, thereby enabling you to write a data file on one
machine and read it on another machine that has a different operating system or file structure.
An application uses a data output stream to write data that can later be read by a program
using a data input stream.
 
Search WWH ::




Custom Search