Download presentation
Presentation is loading. Please wait.
1
File handling and Scanning COMP 112 2017T1
2
Overview Reading and writing from files
to fine Java commands Google “java file IO example” Paths absolute /home/desktop/COMP112 and relative desktop/COMP112 try { risky code } catch { error handling code Scanners
3
Introduction Java file handling uses many Classes including: File
FileReader FileWriter Path Look at the API to find specialised file handling. Scanners transform a string into a sequence of tokens. Frequently the contents of asci files are read using a scanner. Scanners implement the interface Iterator<String>
4
Files Java will find files in the directory from which the program is run just by using the file name. Java IO design is based on the Decorator pattern Thus can lead to unhelpfully complex libraries! Beware java NIO (nonblocking) exists as well My advice is keep it simple and understand the basics File internal representation of a file FileReader for returning one byte at a time BufferedReader for returning one buffer full at a time Scanner for returning one word (or token) at a time
5
Streams and conveyer belts.
Stream processing is a common programming idiom based on manufacturing line: Each person works on the part in front of them. Rate of work is controlled by the conveyer belt. new Scanner(new FileReader("README.TXT"))); Tokens Bytes file new BufferedReader(new FileReader("README.TXT"))); BufferFull Bytes file
6
Risky code Any thing that is risk (opening a file that might not exist) should be performed in a try block try { …} and you need to catch these errors catch { …} and process them. Even if only by printing out an error message. Uncaught errors crash the program!
7
Example From “README.TXT” we build a File then a Scanner.
Build a Scanner File opening can fail Create File representation Failing can throw exceptions Catch IOexceptions from the try block Always Close
8
Paths and Files Files are held in a rooted directory tree structure.
A Complete Path names directories from the root to the file. /home/users/dstr/Comp112/Lectures/foo.ppt A Relative Path names directories from the current location to the file. If the program is run from /home/users/dstr the files relative path is Comp112/Lectures/foo.ppt Note absolute paths start with a / but relative paths do not. Unix and Microsoft computers use paths with different separators. Unix uses / but Microsoft uses \. Java can use File.separator and the JVM will automatically adjust depending on the operating system
9
File Choosing When you do not know the name of the file but want to browse the directories use, s = new Scanner(new File(UIFileChooser.open())); in place of, s =new Scanner(new File("README.TXT"))); DO NOT USE UIFileChooser.open() when you do know the name of the File! Every year students lose marks in the exam by using UIFileChooser.open() to open a file of a given name!
10
Scanner Class The Scanner class provides all the text input methods from the UI class. But can take input from Files s = new Scanner(new File(“README.TXT”)); The following methods you should recognize hasNext, hasNextInt, hasNextBoolean, hasNextDouble next, nextInt, nextBoolean, nextDouble, nextLine Scanner can take as input: File Path String
11
Delimiter Scanner default delimiter is white space that is: the sequence of token the scanner reads are separated by white space. To change the delimitor use s.useDelimiter(",\\s*");
12
Exercises: Read a file where each line can have different number of tokens (words). Output the sequence of tokens and special token to mark where the lines end. Read a file with n integers on each of m lines and output an n*m array of integers.
13
File Writing Writing text to a file All file IO must be in try catch
Reading and writing files is slow!
14
Buffered File Writing To save time Buffer your IO
Note newLine() is platform independent. Data may be stored in the buffer and written to the file when the buffer is full file is closed file is flushed
15
File PrintWriting Buffered output for text: Note println
PrintWriters are buffered and have automatic line flushing!
16
Object IO Most objects can be serialized to class directory
class Student implements Serializable {… This allows them to written to a file and then read back.
17
Overview My advice is keep it simple and understand the basics
File internal representation of a file FileReader/FileWriter for unbuffered reading/writing BufferedReader/BufferedWriter/PrintWriter for buffered reading/writing BufferedReader/PrintWriter for reading/writing lines Scanner for reading tokens (words) ObjectInputStream/ObjectOutputStream for reading/writing Objects Use buffered I/O for Reading/Writing large amounts of data. Data may be lost on failure so flush()buffers.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.