Course List: http://www.c-jump.com/bcc/
A binary file stores data in the same format and with the same number of bytes as is used by that data when it is in the computer's memory:
int data is written in four bytes
double data is written in eight bytes
char data is written in two bytes
boolean data is written in one byte
and so on
Class java.io.DataOutputStream
defined in the java.io.OutputStream class hierarchy
DataOutputStream implements DataOutput interface
DataOutputStream writes primitive Java data types to an output stream in a portable way
the program can read the data back in using the DataInputStream object
Attaching a binary output stream to a file invloves
DataOutputStream writes primitive Java data types to the stream BufferedOutputStream creates a buffer for the stream FileOutputStream connects the stream to a file
Constructors of the classes in the OutputStream hierarchy
Constructor Throws ---------------------------------- ---------------------- DataOutputStream(OutputStream) None BufferedOutputStream(OutputStream) None FileOutputStream(File [, booleanAppend]) FileNotFoundException FileOutputStream(StringPathName [, booleanAppend]) FileNotFoundException
Construct java.io.BufferedOutputStream object
Assign it to OutputStream
Opening a file with a buffer:
FileOutputStream must be instantiated first, and the constructor requires a File object or a file name.
BufferedOutputSream object must be instantiated. The constructor requires the FileOutputStream object.
DataOutputStream object must be instantiated. Its constructor takes the BufferedOutputStream object.
DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("books.bin")));
Note that DataOutputStream implements the DataOutput interface.
DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("data.bin", true)));
System.out is a PrintStream object
System.err is another PrintStream object reserved for error messages
Example using OutputStream to print on the console screen:
|
|
Common methods of the DataOutput interface:
Method Throws
---------------------- -------------
writeBoolean(boolean) IOException
writeInt(int) IOException
writeDouble(double) IOException
writeChar(int) IOException
writeChars(String) IOException
writeUTF(String) IOException
Methods of the DataOutputStream class:
Method Throws -------- ------------- size() None flush() IOException close() IOException
size() returns total number of bytes written to the data output stream so far
Code that writes data to a binary file
DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("books.bin"))); // write a Book object to the file out.writeUTF(book.getCode()); out.writeUTF(book.getDescription()); out.writeDouble(book.getPrice()); // flush data to the file and close the output stream out.close();
Class java.io.DataInputStream
defined in the java.io.InputStream class hierarchy
DataInputStream implements DataInput interface
Attaching a binary input stream to a file involves
DataInputStream reads data from the stream BufferedInputStream creates a buffer for the stream FileInputStream connects the stream to the file
Constructors of the classes in the InputStream hierarchy
Constructor Throws --------------------------------- ---------------------- DataInputStream(InputStream) None BufferedInputStream(InputStream) None FileInputStream(File) FileNotFoundException FileInputStream(StringPathName) FileNotFoundException
Attaching a binary input stream to a file
The FileInputStream object must be instantiated first, its constructor requires a File object or a file name.
The BufferedInputStream object must be instantiated next, its constructor taking the FileInputStream object.
The DataInputStream is instantiated, its constructor taking the BufferedInputStream object
DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("myfile.dat")));
Note that the DataInputStream implements the DataInput interface
Common methods of the DataInput interface
Method Throws -------------- --------------- readBoolean() EOFException readInt() EOFException readDouble() EOFException readChar() EOFException readUTF() EOFException skipBytes(int) EOFException
Common methods of the DataInputStream class
Method Throws ------------ ------------- available() IOException close() IOException
Code that reads Book objects from a binary file
DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("myfile.dat"))); while (in.available() > 0) { // read book data from a file String code = in.readUTF(); String description = in.readUTF(); double price = in.readDouble(); // create the Book object from its data Book p = new Book(code, description, price); } // close the input stream in.close();
There are two ways to read/write binary strings, which results in data stored in two different formats:
writeUTF() writes memory block that takes up two bytes for each character
writeChars() stores strings in Universal Text format (UTF):
first two bytes contain the length of the String
followed by each character stored in a single byte
import java.nio.file.*; import java.io.*; public class UnicodeOutput { public static void main(String[] args) { try { DataOutputStream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream("books.bin"))); // create a test string String testString = "This is a test string.\n"; // use the writeUTF method out.writeUTF(testString); int writeSize1 = out.size(); System.out.println( "writeUTF writes " + writeSize1 + " bytes."); // use the writeChars method out.writeChars(testString); int writeSize2 = out.size() - writeSize1; System.out.println( "writeChars writes " + writeSize2 + " bytes.\n"); out.close(); } catch ( IOException ex ) { ex.printStackTrace(); } } }//class UnicodeOutput
Resulting output
writeUTF writes 25 bytes. writeChars writes 46 bytes.
import java.nio.file.*; import java.io.*; public class UnicodeInput { public static void main(String[] args) { try { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream("myfile.dat"))); // get total bytes int totalBytes = in.available(); // use the readUTF method String string1 = in.readUTF(); int readSize1 = totalBytes - in.available(); System.out.println("readUTF reads " + readSize1 + " bytes."); // use the readChar method int readSize2 = 0; String string2 = ""; int charCount = in.available() / 2; for (int i = 0; i < charCount; i++) { string2 += in.readChar(); readSize2 += 2; } System.out.println("readChar reads " + readSize2 + " bytes.\n"); } catch ( IOException ex ) { } } }//class UnicodeInput
Resulting output from the binary strings
readUTF reads 25 bytes. readChar reads 46 bytes.
The Files.newOutputStream() method
creates a writeable file if it does not already exist
opens the file for writing
returns an OutputStream that can be used to write bytes to the file
newOutputStream() arguments
Path
StandardOpenOption constant (see next slide)
Enum java.nio.file.StandardOpenOption provides modes for file opening:
APPEND -- if the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning.
CREATE -- create a new file if it does not exist.
CREATE_NEW -- create a new file, failing if the file already exists.
DELETE_ON_CLOSE -- delete on close.
DSYNC -- requires that every update to the file's content be written synchronously to the underlying storage device.
READ -- open for read access.
SPARSE -- sparse file.
SYNC -- requires that every update to the file content or metadata be written synchronously to the underlying storage device.
TRUNCATE_EXISTING -- if the file already exists and it is opened for WRITE access, then its length is truncated to 0.
WRITE -- open for write access.
Class java.io.BufferedOutputStream implements buffered output stream for writing raw bytes.
import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; public class FileOut { public static void main(String[] args) { Path file = Paths.get("C:\\example\\Grades.txt"); String s = "ABCDF"; byte[] data = s.getBytes(); OutputStream output = null; try { output = new BufferedOutputStream(Files.newOutputStream(file, CREATE)); output.write(data); output.flush(); output.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }//class FileOut