Java I/O: Writing and Reading Byte-Level and Character-Level Data, Exams of Computer Science

How to use java's dataoutputstream and datainputstream classes to write and read primitive java data types to and from a file in a portable way. It also covers the fileoutputstream, fileinputstream, datainputstream, and dataoutputstream classes for byte-level data, and the printwriter, filewriter, bufferedreader, and filereader classes for character-level data. Examples are provided for writing and reading double values, integers, booleans, and strings.

Typology: Exams

Pre 2010

Uploaded on 08/08/2009

koofers-user-p5s-1
koofers-user-p5s-1 🇺🇸

10 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Saving and Retrieving Byte-Level Data
The DataOutputStream Class
The DataOutputStream lets an application write primitive Java data types to an output stream in a portable
way. They can be read back by using a DataInputStream.
public class DataOutputStream extends FilterOutputStream
implements DataOutput
{ // constructor
public DataOutputStream(OutputStream out)
// selected methods
public final void writeBoolean(boolean v) throws IOException
public final void writeByte(int v) throws IOException
public final void writeChar(int v) throws IOException
public final void writeInt(int v) throws IOException
public final void writeDouble(double v) throws IOException
public final void writeBytes(String s) throws IOException
public final void writeUTF(String str) throws IOException
}
The FileOutputStream Class
A FileOutputStream is used to attach an output stream to a file for writing data.
public class FileOutputStream extends OutputStream
{ // selected constructors
public FileOutputStream(String name)
throws FileNotFoundException
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
public FileOutputStream(File file) throws IOException
}
WARNING: If a FileOutputStream uses an existing file name, the existing file is erased without warning.
The FileInputStream Class
This class obtains input bytes from an existing file and returns an InputStream attached to that file.
public class FileInputStream extends InputStream
{ // selected constructors
public FileInputStream(String name) throws FileNotFoundException
public FileInputStream(File file) throws FileNotFoundException
}
The DataInputStream Class
This class lets an application read primitive Java data types from an underlying input stream in a machine-
independent way. The data should have been written by a DataOutputStream.
public class DataInputStream extends FilterInputStream
implements DataInput
{ // constructor
public DataInputStream(InputStream in)
// selected methods
public final int skipBytes(int n) throws IOException
public final boolean readBoolean() throws EOFException, IOException
public final byte readByte() throws EOFException, IOException
public final char readChar() throws EOFException, IOException
public final int readInt() throws EOFException, IOException
public final double readDouble() throws EOFException, IOException
public final String readUTF() throws EOFException, IOException
}
If any of these methods attempt to read past the end of the stream, an EOFException will be generated.
pf3
pf4

Partial preview of the text

Download Java I/O: Writing and Reading Byte-Level and Character-Level Data and more Exams Computer Science in PDF only on Docsity!

Saving and Retrieving Byte-Level Data

The DataOutputStream Class

The DataOutputStream l ets an application write primitive Java data types to an output stream in a portable

way. They can be read back by using a DataInputStream.

public class DataOutputStream extends FilterOutputStream implements DataOutput { // constructor public DataOutputStream(OutputStream out) // selected methods public final void writeBoolean(boolean v) throws IOException public final void writeByte(int v) throws IOException public final void writeChar(int v) throws IOException public final void writeInt(int v) throws IOException public final void writeDouble(double v) throws IOException public final void writeBytes(String s) throws IOException public final void writeUTF(String str) throws IOException }

The FileOutputStream Class

A FileOutputStream is used to attach an output stream to a file for writing data.

public class FileOutputStream extends OutputStream { // selected constructors public FileOutputStream(String name) throws FileNotFoundException public FileOutputStream(String name, boolean append) throws FileNotFoundException public FileOutputStream(File file) throws IOException }

WARNING: If a FileOutputStream uses an existing file name, the existing file is erased without warning.

The FileInputStream Class

This class obtains input bytes from an existing file and returns an InputStream attached to that file.

public class FileInputStream extends InputStream { // selected constructors public FileInputStream(String name) throws FileNotFoundException public FileInputStream(File file) throws FileNotFoundException }

The DataInputStream Class

This class lets an application read primitive Java data types from an underlying input stream in a machine-

independent way. The data should have been written by a DataOutputStream.

public class DataInputStream extends FilterInputStream implements DataInput { // constructor public DataInputStream(InputStream in) // selected methods public final int skipBytes(int n) throws IOException public final boolean readBoolean() throws EOFException, IOException public final byte readByte() throws EOFException, IOException public final char readChar() throws EOFException, IOException public final int readInt() throws EOFException, IOException public final double readDouble() throws EOFException, IOException public final String readUTF() throws EOFException, IOException }

If any of these methods attempt to read past the end of the stream, an EOFException will be generated.

Example of Reading/Writing Byte-level Data

f s _ o u t o u t D a t a O u t p u t S t r e a m s a m p l e. d a t F i l e O u t p u t S t r e a m import java.io.; public class SimpleOutputTest { public static void main(String args[]) { double Pi = 3.1415; int i = 10; boolean okay = true; char cc = 'J'; String s = "Java by Definition"; try { FileOutputStream fs_out = new FileOutputStream("sample.dat"); DataOutputStream out = new DataOutputStream(fs_out); out.writeDouble(Pi); out.writeInt(i); out.writeBoolean(okay); out.writeChar(cc); out.writeUTF(s); out.close(); } catch(FileNotFoundException fe) { System.err.println(fe); } catch(IOException ioe) { System.out.println(ioe); } } } f s _ i n i n D a t a I n p u t S t r e a m s a m p l e. d a t F i l e I n p u t S t r e a m import java.io.; public class SimpleInputTest { public static void main(String args[]) { try { FileInputStream fs_in = new FileInputStream("sample.dat"); DataInputStream in = new DataInputStream(fs_in); double Pi = in.readDouble(); int i = in.readInt(); boolean okay = in.readBoolean(); char cc = in.readChar(); String s = in.readUTF(); in.close(); System.out.println("Pi = " + Pi + ", i = " + i); System.out.println("okay = " + okay + ", cc = " + cc); System.out.println("s = " + s); } catch(FileNotFoundException fnfe) { System.err.println(fnfe); } catch(IOException ioe) { System.err.println(ioe); } } }

Example:

Create a program that writes a random number of random double values to a file named

"doubles.txt". Then create a second program to read all numbers back and find their average. If

you write a sufficiently large number of double random values between 0 and 1, can you guess

the approximate value of the average you should be getting?

Example:

Create a program that writes two integer values to a file via a data output stream, then open

the same file and attempt to read the data as one double value. Does it work? Explain.

Example of Reading/Writing Character-level Data

f w _ o u t b f w _ o u t B u f f e r e d W r i t e r s a m p l e. d a t F i l e W r i t e r o u t P r i n t W r i t e r

Example:

Create a program to write “Hello World” to a text file, each word in one line.

f _ r e a d e r r e a d e r B u f f e r e d R e a d e r s a m p l e. d a t F i l e R e a d e r

Example:

Create a program to read a text file with an unknown number of lines. The program should print out

each line, prefaced by a sequential line number.

Definition: The File Class

The File class is used to represent a file, a directory name, or a combination of directory names and file. The file

names used are highly system-dependent, but the File class provides convenient methods to access and

manipulate files in a system-independent manner. The Java API defines File as follows:

public class File extends Object implements Serializable, Comparable { // constructor public File(String pathname) // selected fields public static final String separator // selected methods public String getName() public String getPath() public URL toURL() throws MalformedURLException public boolean exists() public boolean isDirectory() public boolean isFile() public long length() public boolean delete() public File[] listFiles() public File[] listFiles(FileFilter filter) public boolean mkdir() public boolean mkdirs() public boolean renameTo(File dest) }