file class in java
play

File class in Java n Programmers refer to input/output as - PDF document

10/31/15 File class in Java n Programmers refer to input/output as "I/O". n Input is received from the keyboard, mouse, files. File Input and Output output is sent to the console, monitor, files, (Savitch, Chapter 10)


  1. 10/31/15 ¡ File class in Java n Programmers refer to input/output as "I/O". n Input is received from the keyboard, mouse, files. File Input and Output output is sent to the console, monitor, files, … (Savitch, Chapter 10) n The File class represents files as objects, and is defined in the java.io package. TOPICS n Creating a File object allows you to get information about a file (on the hard disk or optical drive). • File Input n Creating a File object does NOT create a new file on • Exception Handling your disk. • File Output File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); } CS 160, Fall Semester 2015 2 File methods Scanner reminder n Some methods in the File class: n The Scanner class reads input and processes strings Method name Description and numbers from the user. n When constructor is called with System.in , the character returns whether file can be canRead() stream is input typed to the console. read n Instantiate Scanner by passing the input character removes file from disk delete() stream to the constructor: whether this file exists on disk exists() Scanner scan = new Scanner(System.in); returns name of file getName() returns number of characters length() in file renameTo( filename ) changes name of file CS 160, Fall Semester 2015 3 CS 160, Fall Semester 2015 4 1 ¡

  2. 10/31/15 ¡ Scanner reminder Scanner for reading a file n To read a file, pass a File object as a parameter when n Common methods called on Scanner : constructing a Scanner String variable q Read a line n Scanner for a file: or string literal String str = scan.nextLine(); Scanner <name> = new Scanner(new File( <filename> )); q Read a string (separated by whitespace) n Example: String str = scan.next( ); Scanner scan = new Scanner(new File("numbers.txt")); q Read an integer n or: int ival = scan.nextInt( ); q Read a double File file = new File("numbers.txt"); double dval = scan.nextDouble( ); 
 Scanner scan= new Scanner(file); CS 160, Fall Semester 2015 5 CS 160, Fall Semester 2015 6 File names and paths File names and paths n relative path : does not specify any top-level folder, so n When you construct a File object with a relative path, Java the path is relative to the current directory: assumes it is relative to the current directory . q In Directory : "names.dat" Scanner scan = q In Subdirectory : "code/Example.java" new Scanner(new File("data/input.txt")); n absolute path : The complete pathname to a file starting q If our program is in ~/workspace/P4 at the root directory /: q Scanner will look for ~/workspace/P4/data/input.txt q In Linux : "/users/cs160/programs/Example.java" q In Windows: "C:/Documents/cs160/programs/data.csv" CS 160, Fall Semester 2015 7 CS 160, Fall Semester 2015 8 2 ¡

  3. 10/31/15 ¡ Compiler error with files Compiler error with files n Here is the compilation error that is produced: n Question: Why will the following program NOT compile? ReadFile.java:6: unreported exception import java.io.*; // for File java.io.FileNotFoundException; import java.util.*; // for Scanner must be caught or declared to be thrown Scanner scan = new Scanner(new File("data.txt")); public class ReadFile { n The problem has to do with error reporting. public static void main(String[] args) { File file = new File("input.txt"); n What to do when a file cannot be opened? Scanner scan = new Scanner(file); n File may not exist, or may be protected. String text = scan.next(); n Options: exit program, return error, or throw exception System.out.println(text); n Exceptions are the normal error mechanism in Java. } } n Answer: Because of Java exception handling! CS 160, Fall Semester 2015 9 CS 160, Fall Semester 2015 10 Exceptions Checked exceptions n exception : An object that represents a program n checked exception : An error that must be error. handled by our program (otherwise it will not q Programs with invalid logic will cause exceptions. compile). q Examples: q We must specify what our program will do to handle dividing by zero n any potential file I/O failures. calling charAt on a String with an out of range index n trying to read a file that does not exist q We must either: n declare that our program will handle (" catch ") the exception, or q We say that a logical error results in an exception n being thrown . state that we choose not to handle the exception (and we n accept that the program will crash if an exception occurs) q It is also possible to catch (handle) an exception. CS 160, Fall Semester 2015 11 CS 160, Fall Semester 2015 12 3 ¡

  4. 10/31/15 ¡ Throwing Exceptions Handling Exceptions n throws clause : Keywords placed on a method's header n When doing file I/O, we use IOException . to state that it may generate an exception. public static void main(String[] args) { n It's like a waiver of liability: try { q "I hereby agree that this method might throw an exception, and I File file = new File(“input.txt”); accept the consequences (crashing) if this happens.” Scanner scan = new Scanner(file); q General syntax: String firstLine = scan.nextLine(); public static <type> <name> ( <params> ) throws <type> ... { … } } catch (IOException e) { q When doing file open, we throw IOException . System.out.println(“Unable to open input.txt”); public static void main(String[] args) System.exit(-1); throws IOException { } } CS 160, Fall Semester 2015 13 CS 160, Fall Semester 2015 14 Fixing the compiler error Using Scanner to read a file n Consider a file numbers.txt that contains n Throwing an exception or handling the exception both this text: resolve the compiler error. 308.2 n Throwing Exceptions: User will see program terminate 14.9 7.4 2.8 with exception, that’s not very friendly. 3.9 4.7 -15.4 n Handling Exceptions: User gets a clear indication of 2.8 problem with error message, that’s much better. n A Scanner views all input as a stream of n We will handle exceptions when reading and writing files in programming assignments. characters: q 308.2\n\t14.9 7.4 2.8\n\n3.9 4.7\t-15.4\n\t2.8\n CS 160, Fall Semester 2015 15 CS 160, Fall Semester 2015 16 4 ¡

  5. 10/31/15 ¡ Consuming tokens First problem n Each call to next / nextLine / nextInt / nextDouble , n Write code that reads the first 5 double etc. advances the position of the scanner to the end of values from a file and prints. the current token, skipping over any whitespace: 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n ^ scan.nextDouble(); 308.2 \n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n ^ scan.nextDouble(); 308.2\n 14.9 7.4 2.8\n\n\n3.9 4.7 -15.4\n2.8\n ^ CS 160, Fall Semester 2015 17 CS 160, Fall Semester 2015 18 First solution Second problem public static void main(String[] args) n How would we modify the program to read all try { the file? File file = new File(“input.txt”); Scanner scan = new Scanner(file); for (int i = 0; i <= 4; i++) { double next = scan.nextDouble(); System.out.println("number = " + next); } } catch (IOException e) { System.out.println(“Unable to open input.txt”); System.exit(-1); } } CS 160, Fall Semester 2015 19 CS 160, Fall Semester 2015 20 5 ¡

  6. 10/31/15 ¡ Second solution Refining the problem public static void main(String[] args) n Modify the program again to handle files that try { also contain non-numeric tokens. File file = new File(“input.txt”); Scanner scan = new Scanner(file); q The program should skip any such tokens. while (scan.hasNextDouble() { n For example, it should produce the same double next = scan.nextDouble(); output as before when given this input file: System.out.println("number = " + next); } } catch (IOException e) { 308.2 hello System.out.println(“Unable to open input.txt”); 14.9 7.4 bad stuff 2.8 System.exit(-1); 3.9 4.7 oops -15.4 } :-) 2.8 @#*($& } CS 160, Fall Semester 2015 21 CS 160, Fall Semester 2015 22 Refining the program Reading input line-by-line n Given the following input data: while (scan.hasNext()) { 23 3.14 John Smith "Hello world" 45.2 19 if (scan.hasNextDouble()) { n The Scanner can read it line-by-line: double next = scan.nextDouble(); 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n System.out.println("number = " + next); ^ } else { scan.nextLine(); 23\t3.14 John Smith\t"Hello world" \n\t\t45.2 19\n // consume the bad token ^ scan.next(); scan.nextLine(); 23\t3.14 John Smith\t"Hello world"\n \t\t45.2 19 \n } ^ } n The \n character is consumed but not returned. CS 160, Fall Semester 2015 23 CS 160, Fall Semester 2015 24 6 ¡

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend