1 of 28

Streams & Files

CS 240 – Advanced Programming Concepts

2 of 28

I/O Overview

3 of 28

Ways to Read/Write Files

  • Streams
    • Read or write a file (or other source or destination of bytes) sequentially
  • Scanner Class
    • Tokenize stream input (read one token at a time)
  • Files Class
    • Read, copy, etc. whole files
  • RandomAccessFile Class
    • Use a file pointer to read from / write to any location in a file

4 of 28

The File Class

  • Used to represent, create, or delete a file, but not to read one
  • Check file existence:

       File file = new File("/user/MyFile.txt");

       if(file.exists()) {

  • Create a file:

       File file = new File("/user/MyFile.txt");

       file.createNewFile();

  • Delete a file:

       File file = new File("/user/MyFile.txt");

       file.delete();

5 of 28

Blank

6 of 28

Streams

Reading and Writing Bytes

7 of 28

Java I/O Streams (overview)

  • Writing data to / Reading data from files (or other data sources)
  • Two Choices: Binary-Formatted or Text-Formatted Data
    • Binary Formatted: 00 00 04 D2 (4 bytes)
    • Text Formatted: 1234 (4 characters)
  • InputStream and OutputStream
    • Reading/writing bytes
    • Reading/writing binary-formatted data
  • Reader and Writer
    • Reading/writing characters
    • Reading/writing text-formatted data

8 of 28

Reading/Writing Bytes

  • The InputStream interface is used to read bytes sequentially from a data source
    • FileInputStream
    • PipedInputStream
    • URLConnection.getInputStream()
    • HttpExchange.getRequestBody()
    • ResultSet.getBinaryStream(int columnIndex)
    • Many more examples in the Java API

9 of 28

Filter Input Streams

  • There are many features you may want to enable when consuming data from an InputStream
    • Decompress data as it comes out of the stream
    • Decrypt data as it comes out of the stream
    • Compute a “digest” of the stream (a fixed-length value that summarizes the data in the stream)
    • Byte counting
    • Line Counting
    • Buffering

10 of 28

Filter Input Streams (cont.)

  • Open an InputStream on a data source (file, socket, etc.), and then wrap it in one or more “filter input streams” that provide the features you want (decompression, decryption, etc.)

  • Filter input streams all implement the InputStream interface, and can be arranged as a pipeline with the real data source at the end

  • Each filter input stream reads data from the next InputStream in line, and then performs a transformation or calculation on the data

11 of 28

OutputStream

  • Writing bytes works the same way, just in reverse
  • The OutputStream interface is used to write bytes sequentially to a data destination
    • FileOutputStream
    • PipedOutputStream
    • URLConnection.getOutputStream()
    • HttpExchange.getResponseBody()
    • Many more examples in the Java API

12 of 28

Filter Output Streams

  • There are many features you may want to enable when writing data to an OutputStream
    • Compress data as it goes into the stream
    • Encrypt data as it goes into the stream
    • Compute a “digest” of the stream (a fixed-length value that summarizes the data in the stream)
    • Buffering

13 of 28

Filter Output Streams (cont.)

  • Open an OutputStream on a data destination (file, socket, etc.), and then wrap it in one or more “filter output streams” that provide the features you want (compression, encryption, etc.)

  • Filter output streams all implement the OutputStream interface, and can be arranged as a pipeline with the real data destination at the end

  • Each filter output stream performs a transformation or calculation on the data, and then writes it to the next OutputStream in line

14 of 28

Filter Stream Example

  • Compress a file to GZIP format
    • Compress Example
    • LegacyCompress Example
  • Decompress a file from GZIP format
    • Decompress Example
    • LegacyDecompress Example

15 of 28

Reading/Writing Binary-Formatted Data

  • Reading/writing bytes is useful, but usually we want to read/write larger data values, such as: float, int, boolean, etc.

  • The DataOutputStream class lets you write binary-formatted data values

  • The DataOutputStream(OutputStream out) constructor wraps a DataOutputStream around any OutputStream

  • The DataInputStream class lets you read binary-formatted data values

  • The DataInputStream(InputStream in) constructor wraps a DataInputStream around any InputStream

16 of 28

Blank

17 of 28

Readers and Writers

Reading and Writing Character Data

18 of 28

Reading/Writing Characters

  • The Reader interface is used to read characters sequentially from a data source

  • The Writer interface is used to write characters sequentially to a data destination

  • See CopyFileExample

19 of 28

Reading/Writing Text-Formatted Data

  • The PrintWriter class lets you write text-formatted data values (String, int, float, boolean, etc.)

  • The Scanner class lets you read text-formatted data values

20 of 28

Convert from Streams to Readers or Writers 

  • Convert from an input stream to a reader with InputStreamReader:

new InputStreamReader(new FileInputStream(“myfile.txt”));

  • Convert from an output stream to a writer with OutputStreamWriter:

new OutputStreamWriter(new FileOutputStream(“myfile.txt”));

21 of 28

Blank

22 of 28

The Scanner Class

Tokenizing Input

23 of 28

Scanner: Tokenize Data As You Read It

  • Can read "tokens" one at a time from a source of characters
  • Read from a File, InputStream, or Reader
  • Can specify the delimit character(s) as a regular expression
    • Defaults to delimiting by whitespace: \s+

  • Code Examples:

24 of 28

Blank

25 of 28

Other Ways to Read and Write Files

26 of 28

Files: Read Entire File into a List

public List<String> readFile(File file) throws IOException {� Path path = Paths.get(file.getPath());� List<String> fileContents = Files.readAllLines(path); � return fileContents; �}

27 of 28

Random Access Files

  • The RandomAccessFile class allows “random access” to a file’s contents for both reading and writing

  • Random Access
    • The “file pointer” represents the current location in the file (similar to an array index)
    • Use the seek(long) or skipBytes(int) methods to move the “file pointer” to any location in the file
    • Read or write bytes at the current file pointer location using various overloaded read and write methods

28 of 28

Blank