file class in java
play

File class in Java Programmers refer to input/output as - PowerPoint PPT Presentation

File class in Java Programmers refer to input/output as "I/O". Input is received from the keyboard, mouse, files. output is sent to the console, monitor, files, File Input and Output The File class represents files as


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

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

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

  4. Throwing Exceptions Handling Exceptions ■ throws clause : Keywords placed on a method's header ■ When doing file I/O, we use IOException . to state that it may generate an exception. public static void main(String[] args) { ■ It's like a waiver of liability: try { "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); General syntax: ❑ String firstLine = scan.nextLine(); public static <type> <name> ( <params> ) throws <type> ... { … } } catch (IOException e) { 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, Summer Semester 2016 13 CS 160, Summer Semester 2016 14 Fixing the compiler error Using Scanner to read a file ■ Consider a file numbers.txt that contains ■ Throwing an exception or handling the exception both this text: resolve the compiler error. 308.2 ■ 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 ■ Handling Exceptions: User gets a clear indication of 2.8 problem with error message, that’s much better. ■ A Scanner views all input as a stream of ■ We will handle exceptions when reading and writing files in programming assignments. characters: 308.2\n\t14.9 7.4 2.8\n\n3.9 4.7\t-15.4\n\t2.8\n ❑ CS 160, Summer Semester 2016 15 CS 160, Summer Semester 2016 16

  5. Consuming tokens First problem ■ Each call to next / nextLine / nextInt / nextDouble , ■ 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, Summer Semester 2016 17 CS 160, Summer Semester 2016 18 First solution Second problem public static void main(String[] args) ■ 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, Summer Semester 2016 19 CS 160, Summer Semester 2016 20

  6. Second solution Refining the problem public static void main(String[] args) ■ 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); ❑ The program should skip any such tokens. while (scan.hasNextDouble() { ■ 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, Summer Semester 2016 21 CS 160, Summer Semester 2016 22 Refining the program Reading input line-by-line Given the following input data: ■ while (scan.hasNext()) { 23 3.14 John Smith "Hello world" 45.2 19 if (scan.hasNextDouble()) { 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 } ^ The \n character is consumed but not returned. ■ CS 160, Summer Semester 2016 23 CS 160, Summer Semester 2016 24

Recommend


More recommend