Download presentation
Presentation is loading. Please wait.
1
CSS161: Fundamentals of Computing
File I/O This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the professor’s own class materials. CSS161: Fundamentals of Computing
2
CSS161: Fundamentals of Computing
Streams Stream: an object that enables the flow of datat between a program and external peripherals. Input stream: data flows into a program System.in FileInputStream Socket.getInputStream( ) Output stream: data flows out of a program System.out FileOutputStream Socket.getOutputStream( ) program Eat my shorts. program The quick brown fox…. CSS161: Fundamentals of Computing
3
Text Files and Binary Files
ASCII files that encode data into man-readable character set. Binary Files Binary digits that are machine code but not man-readable. More efficient to process than text files Smaller space No ASCII to primary data conversion CSS161: Fundamentals of Computing
4
CSS161: Fundamentals of Computing
Writing to a Text File Open a file FileOutputStream outFile = new FileOutputStream( “filename” ); Filter an output stream PrintWriter outputStream = new PrintWriter( outFile ); Write data through the stream outputStream.println( “This is a text to write” ); Close the file outputStream.close( ); CSS161: Fundamentals of Computing
5
Opening a File for Writing
new FileOutputStream( “filename” ) Let the underlying Operating System create a file if necessary and mark the file in writing. Set a position to write texts from the top of the file Need to incorporate system-provided classes: import java.io.FileOutputStream; import java.io.FileNotFoundException; Get prepared to deal with an exception “file not found” in case if filename is unknown. try { // open a file } catch( FileNotFoundException e ) { // handle an error } CSS161: Fundamentals of Computing
6
Creating a Filter for Output Stream
Syntax FileOutputStream outFile = new FileOutputStream( “filename” ); PrintWriter outputStream = new PrintWriter( outFile ); Need to incorporate a system-provided classe: import java.io.PrintWriter; Filter a file output stream import java.io.FileOutputStream; import java.io.FileNotFoundException; // the below is within main( ) PrintWriter outputStream = null; try { outputStream = new PrintWriter( new FileOutputStream( “data.txt” ) ); } catch ( FileNotFoundException e ) System.out.println( “Error opening the file data.txt” ); System.exit( 0 ); Can be replaced with just import java.io.*; Why can’t we declare it within try? Where is outFile? CSS161: Fundamentals of Computing
7
Writing Texts to Output Stream
println( argument ) writes to a given file an argument that can be a string, character, integer, floating-point nmber, boolean, or any combination of these, connected with + signs. A new line is added. Example: outputStream.println( “result = ” + result ); print( argument ) Is the same as println( ) except no new line added. outputStream.print( “sum = ” + (a + b) ); printf( format, arguments ) Is the same as System.out.printf( ) except that arguments are written to a file. outputStream.printf( “value = %f%n” + value ); CSS161: Fundamentals of Computing
8
CSS161: Fundamentals of Computing
Closing a File close( ); The underlying Operating System will: Flush out all on-going writes to a given file. Put an EOF (end of file) mark at the end of the file. Reset the file from in-writing to unused. CSS161: Fundamentals of Computing
9
Example - Writing to a Text File
import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class TextFileOutputDemo{ public static void main(String[] args) { PrintWriter outputStream = null; try outputStream = new PrintWriter(new FileOutputStream("stuff.txt")); } catch(FileNotFoundException e) System.out.println("Error opening the file stuff.txt."); System.exit(0); System.out.println("Writing to file."); outputStream.println("The quick brown fox"); outputStream.println("jumped over the lazy dog."); outputStream.close( ); System.out.println("End of program."); Open a file Create a fileter Write texts Close the file CSS161: Fundamentals of Computing
10
PITFALL: Overwriting an Output File
To open a file for writing: outputStream = new PrintWriter( new FileOutputStream( “data.txt” ) ); Create a file if data.txt does not exist. Delete old contents if data.txt exists. Thus, always start with an empty file To append data to an existing file: new PrintWriter( new FileOutputStream( “data.txt” ), true ); Previous contents Newly add contents CSS161: Fundamentals of Computing
11
CSS161: Fundamentals of Computing
Self-Test Exercises Work on Textbook p573’s exercises 3 ~ 7 CSS161: Fundamentals of Computing
12
Reading from a Text File
Open a file FileInputStream inFile = New FileInputStream( “filename” ); Filter an input stream Scanner inputStream = new Scanner( inFile ); Write data through the stream outputStream.nextInt( ); outputStream.nextLong( ); outputStream.next( ); outputSstream.nextLine( ); etc. Close the file inputStream.close( ); CSS161: Fundamentals of Computing
13
Opening a File for Reading
new FileInputStream( “filename” ) Let the underlying Operating System mark a file in read. This means other programs can no longer modify the same file concurrently but still can read the file. Set a reading position to the top of the given file. Need to incorporate system-provided classes: import java.io.FileInputStream; import java.io.FileNotFoundException; Get prepared to deal with an exception “file not found” in case if filename is unknown. try { // open a file } catch( FileNotFoundException e ) { // handle an error } CSS161: Fundamentals of Computing
14
Creating a Filter for Input Stream
Syntax FileInputStream inFile = new FileInputStream( “filename” ); Scanner inputStream = new Scanner( inFile ); Need to incorporate a system-provided classe: import java.io.Scanner; Filter a file input stream import java.io.FileInputStream; import java.io.FileNotFoundException; // the below is within main( ) Scanner inputStream = null; try { inputStream = new Scanner( new FileInputStream( “data.txt” ) ); } catch ( FileNotFoundException e ) System.out.println( “The file data.txt was not found.” ); System.exit( 0 ); Can be replaced with just import java.io.*; Why can’t we declare it within try? Where is inFile? Unlike FileOutputStream, FileInputStream needs an existing file. CSS161: Fundamentals of Computing
15
Reading Data from a Text File
Exception public int nextInt( ); Returns the next token as int. public long nextLong( ); Returns the next token as long. public byte nextByte( ); Returns the next token as byte. public short nextShort( ); Returns the next token as short. public double nextDouble( ); Returns the next token as double. public float nextFloat( ); Returns the next token as float. public boolean nextBoolean( ); Returns the next token as boolean. public String next( ); Returns the next token. public String nextLine( ); Returns the rest of the current input line. The line terminater ‘\n’ is read and discarded. public Scanner useDelimiter( String newDelimiter ); Changes the delimiter for input . readable true hello 4567 false readable Exception readable Exception readable CSS161: Fundamentals of Computing
16
Checking More Data to Read
To avoid NoSuchElementException Call hasNext( ) that returns false if there are no more tokens. To avoid InputMismatchException Call hasNext***( ) before calling has***( ) where *** is Int, Long, Byte, Short, Double, Float and Boolean To avoid IllegalStateException No more calls of any functions of scanner after closing scanner, (I.e., calling close( )). CSS161: Fundamentals of Computing
17
CSS161: Fundamentals of Computing
Closing a File close( ); The underlying Operating System will: Reset the file status from in-read to unused. This means other programs can now modify the same file. CSS161: Fundamentals of Computing
18
Example 1 - Reading from a Text File (1 of 2)
CSS161: Fundamentals of Computing
19
Example 1 - Reading from a Text File (2 of 2)
CSS161: Fundamentals of Computing
20
Example 2 - Checking for EOF (1 of 2)
CSS161: Fundamentals of Computing
21
Example 2 - Checking for EOF (1 of 2)
CSS161: Fundamentals of Computing
22
CSS161: Fundamentals of Computing
Self-Test Exercises Work on Textbook p583’s exercises 8 ~ 11. CSS161: Fundamentals of Computing
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.