Docsity

File class in Java File methods Scanner reminder, Exams of Java Programming

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

Partial preview of the text

Download File class in Java File methods Scanner reminder and more Exams Java Programming in PDF only on Docsity!

File Input and Output

(Savitch, Chapter 10)

TOPICS

  • File Input
  • Exception Handling
  • File Output

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, … ■ The File class represents files as objects, and is defined in the java.io package. ■ Creating a File object allows you to get information about a file (on the hard disk or optical drive). ■ Creating a File object does NOT create a new file on your disk. File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); }

CS 160, Summer Semester 2016 2

File methods

■ Some methods in the File class:

Method name Description

canRead() returns whether file can be

read

delete() removes file from disk

exists() whether this file exists on disk

getName() returns name of file

length() returns number of characters

in file

renameTo( filename ) changes name of file

Scanner reminder

■ The Scanner class reads input and processes strings

and numbers from the user.

■ The constructor can be called with the following three

arguments:

❑ A String literal

■ Scanner scan = new Scanner(“Hello there”);

❑ System.in

■ Scanner scan = new Scanner(System.in);

❑ A File object

■ Scanner scan = new Scanner(new File());

Scanner reminder

■ Common methods called on Scanner :

❑ Read a line String str = scan.nextLine(); ❑ Read a string (separated by whitespace) String str = scan.next( ); ❑ Read an integer int ival = scan.nextInt( ); ❑ Read a double double dval = scan.nextDouble( );

CS 160, Summer Semester 2016^5

Scanner for reading a file

■ To read a file, pass a File object as a parameter when

constructing a Scanner

■ Scanner for a file:

Scanner = new Scanner(new File( ));

■ Example:

Scanner scan = new Scanner(new File("numbers.txt"));

■ or:

File file = new File("numbers.txt"); Scanner scan= new Scanner(file);

String variable or string literal

6 CS 160, Summer Semester 2016

File names and paths

■ relative path : does not specify any top-level folder, so

the path is relative to the current directory:

❑ In Directory: "names.dat" ❑ In Subdirectory: "code/Example.java"

■ absolute path : The complete pathname to a file starting

at the root directory /:

❑ In Linux: "/users/cs160/programs/Example.java" ❑ In Windows: "C:/Documents/cs160/programs/data.csv"

File names and paths

■ When you construct a File object with a relative path, Java

assumes it is relative to the current directory.

Scanner scan =

new Scanner(new File("data/input.txt"));

❑ If our program is in ~/workspace/P ❑ Scanner will look for ~/workspace/P4/data/input.txt

Throwing Exceptions

■ throws clause : Keywords placed on a method's header

to state that it may generate an exception.

■ It's like a waiver of liability:

❑ "I hereby agree that this method might throw an exception, and I accept the consequences (crashing) if this happens.” ❑ General syntax: public static ( ) throws { … } ❑ When doing file open, we throw IOException. public static void main(String[] args) throws IOException {

CS 160, Summer Semester 2016^13

Handling Exceptions

■ When doing file I/O, we use IOException.

public static void main(String[] args) { try { File file = new File(“input.txt”); Scanner scan = new Scanner(file); String firstLine = scan.nextLine(); ... } catch (IOException e) { System.out.println(“Unable to open input.txt”); System.exit(-1); } } CS 160, Summer Semester 2016^14

Fixing the compiler error

■ Throwing an exception or handling the exception both

resolve the compiler error.

■ Throwing Exceptions: User will see program terminate

with exception, that’s not very friendly.

■ Handling Exceptions: User gets a clear indication of

problem with error message, that’s much better.

■ We will handle exceptions when reading and writing files

in programming assignments.

Using Scanner to read a file

■ Consider a file numbers.txt that contains

this text:

14.9 7.4 2.

3.9 4.7 -15.

■ A Scanner views all input as a stream of

characters:

❑ 308.2\n\t14.9 7.4 2.8\n\n3.9 4.7\t-15.4\n\t2.8\n

Consuming tokens

■ Each call to next/nextLine/nextInt/nextDouble,

etc. advances the position of the scanner to the end of

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

First problem

■ Write code that reads the first 5 double

values from a file and prints.

CS 160, Summer Semester 2016^18

First solution

public static void main(String[] args) try { 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); } }

Second problem

■ How would we modify the program to read all

the file?

File processing question

■ Write a program that reads a text file and

adds line numbers at the beginning of each

line

CS 160, Summer Semester 2016^25

Solution

int count = 0; while (scan.hasNextLine()) { String line = scan.nextLine(); System.out.println(count + “ “ + line); count++; }

CS 160, Summer Semester 2016^26

Problem

■ Given a file with the following contents:

123 Susan 12.5 8.1 7.6 3.

456 Brad 4.0 11.6 6.5 2.7 12

789 Jennifer 8.0 8.0 8.0 8.0 7.

❑ Consider the task of computing hours worked by each

person

❑ Approach:

■ Break the input into lines. ■ Break each line into tokens.

Scanner on Strings

■ A Scanner can tokenize a String, such as a line of a file.

Scanner = new Scanner( );

❑ Example:

String text = "1.4 3.2 hello 9 27.5"; Scanner scan = new Scanner(text); System.out.println(scan.next()); // 1. System.out.println(scan.next()); // 3. System.out.println(scan.next()); // hello

Tokenize an entire file

■ We can use string Scanner(s) to tokenize each line of

a file:

Scanner scan = new Scanner(new File( )); while (scan.hasNextLine()) { String line = scan.nextLine(); Scanner lineScan = new Scanner(line); }

CS 160, Summer Semester 2016^29

Entire Example

Scanner scan = new Scanner(new File("input.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); Scanner lineScan = new Scanner(line); int count = 0; while (lineScan.hasNext()) { String token = lineScan.next(); count++; } System.out.println("Line has “+count+" tokens"); } Input file input.txt: 23 3.14 John Smith "Hello world" 45.2 19

Output to console: Line has 6 tokens Line has 2 tokens CS 160, Summer Semester 2016^30

Opening a file for writing

■ Same story as reading, we must handle exceptions:

public static void main(String[] args) { try { File file = new File(“output.txt”); PrintWriter output = new PrintWriter(file); output.println(“Integer number: ” + 987654); ... } catch (IOException e) { System.out.println(“Unable to write output.txt”); System.exit(-1); }

File output

■ You can output all the same things as you would with

System.out.println:

■ Discussion so far has been limited to text files.

output.println(”Double: " + 123.456); output.println("Integer: " + 987654); output.println("String: " + "Hello There");

■ Binary files store data as numbers, not characters.

■ Binary files are not human readable, but more efficient.