InputOutput - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

InputOutput

Description:

Failure at any point results in an IOException. Implementing Text Input from a File ... catch(IOException e) { something went wrong with reading or closing ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 8
Provided by: Tom3249
Category:

less

Transcript and Presenter's Notes

Title: InputOutput


1
Input/Output
  • Input-output is particularly error-prone
  • It involves interaction with the external
    environment
  • The javaio package supports input-output
  • javaioIOException is a checked exception

2
Readers, Writers, Streams
  • Readers and writers deal with textual input
  • Based upon the char type
  • Streams deal with binary data
  • Based around the byte type
  • The address-book-io project illustrates textual IO

3
Text Output to a File
  • Use the FileWriter class
  • Open a file
  • Write to the file
  • Close the file
  • Failure at any point results in an IOException

4
Implementing File Output
try FileWriter writer new
FileWriter("name of file") while(there is
more text to write)
writerwrite(next piece of text)
writerclose() catch(IOException e)
something went wrong with accessing the file
5
Text Input from File
  • Use the FileReader class
  • Use BufferedReader for line-based input
  • Open a file
  • Read from the file
  • Close the file
  • Failure at any point results in an IOException

6
Implementing Text Input from a File
try BufferedReader reader new
BufferedReader(new FileReader("filename"))
String line readerreadLine() while(line !
null) do something with line
line readerreadLine()
readerclose() catch(FileNotFoundException e)
the specified file could not be
found catch(IOException e) something went
wrong with reading or closing
7
Text Input from the Terminal
  • Systemin maps to the terminal
  • javaioInputStream
  • Often wrapped in a javautilScanner
  • Scanner supports parsing of textual input
  • nextInt, nextLine
  • Scanner with File an alternative to
    BufferedReader with FileReader
Write a Comment
User Comments (0)
About PowerShow.com