SlideShare a Scribd company logo
File Input and Output
TOPICS
• File Input
• Exception Handling
• File Output
File class in Java
 Programmers refer to input/output as "I/O".
 The File class represents files as objects.
 The class is defined in the java.io package.
 Creating a File object allows you to get information
about a file on the disk.
 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();
}
2
Files
 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
Scanner reminder
 The Scanner class reads input and processes strings
and numbers from the user.
 When constructor is called with System.in, the character
stream is input typed to the console.
 Instantiate Scanner by passing the input character
stream to the constructor:
Scanner scan = new Scanner(System.in);
4
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( );
5
Opening a file for reading
 To read a file, pass a File object as a parameter when
constructing a Scanner
 Scanner for a file:
Scanner <name> = new Scanner(new File(<filename>));
 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
File names and paths
 relative path: does not specify any top-level folder, so
the path is relative to the current directory:
 "names.dat"
 "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”
7
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/P4
 Scanner will look for ~/workspace/P4/data/input.txt
8
Compiler error with files
 Question: Why will the following program NOT compile?
import java.io.*; // for File
import java.util.*; // for Scanner
public class ReadFile {
public static void main(String[] args) {
File file = new File(“input.txt”);
Scanner scan = new Scanner(file);
String text = scan.next();
System.out.println(text);
}
}
 Answer: Because of Java exception handling!
9
Compiler error with files
 Here is the compilation error that is produced:
ReadFile.java:6: unreported exception
java.io.FileNotFoundException;
must be caught or declared to be thrown
Scanner scan = new Scanner(new File("data.txt"));
 The problem has to do with error reporting.
 What to do when a file cannot be opened?
 File may not exist, or may be protected.
 Options: exit program, return error, or throw exception
 Exceptions are the normal error mechanism in Java.
10
Exceptions
 exception: An object that represents a program
error.
 Programs with invalid logic will cause exceptions.
 Examples:
 dividing by zero
 calling charAt on a String with an out of range index
 trying to read a file that does not exist
 We say that a logical error results in an exception
being thrown.
 It is also possible to catch (handle) an exception.
11
Checked exceptions
 checked exception: An error that must be
handled by our program (otherwise it will not
compile).
 We must specify what our program will do to handle
any potential file I/O failures.
 We must either:
 declare that our program will handle ("catch") the exception, or
 state that we choose not to handle the exception
(and we accept that the program will crash if an exception
occurs)
12
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 <type> <name>(<params>) throws <type>
{ … }
 When doing file open, we throw IOException.
public static void main(String[] args)
throws IOException {
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);
}
}
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.
15
Using Scanner to read file data
 Consider a file numbers.txt that contains
this text:
308.2
14.9 7.4 2.8
3.9 4.7 -15.4
2.8
 A Scanner views all input as a stream of
characters:
 308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
16
Consuming tokens
 Each call to next, nextInt, nextDouble, etc.
advances the position of the scanner to the end of the
current token, skipping over any whitespace:
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
scan.nextDouble();
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
scan.nextDouble();
308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n
^
17
First problem
 Write code that reads the first 5 double
values from a file and prints.
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);
}
}
19
Second problem
 How would we modify the program to read all
the file?
20
Second solution
public static void main(String[] args)
try {
File file = new File(“input.txt”);
Scanner scan = new Scanner(file);
while (scan.hasNextDouble() {
double next = scan.nextDouble();
System.out.println("number = " + next);
}
} catch (IOException e) {
System.out.println(“Unable to open input.txt”);
System.exit(-1);
}
}
21
Refining the problem
 Modify the program again to handle files that
also contain non-numeric tokens.
 The program should skip any such tokens.
 For example, it should produce the same
output as before when given this input file:
308.2 hello
14.9 7.4 bad stuff 2.8
3.9 4.7 oops -15.4
:-) 2.8 @#*($&
22
Refining the program
while (scan.hasNext()) {
if (scan.hasNextDouble()) {
double next = scan.nextDouble();
System.out.println("number = " + next);
} else {
// consume the bad token
scan.next();
}
}
23
Reading input line-by-line
 Given the following input data:
23 3.14 John Smith "Hello world"
45.2 19
 The Scanner can read it line-by-line:
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
scan.nextLine()
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
scan.nextLine()
23t3.14 John Smitht"Hello world"ntt45.2 19n
^
 The n character is consumed but not returned.
24
File processing question
 Write a program that reads a text file and
adds line numbers at the beginning of each
line
25
Solution
int count = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(count + “ “ + line);
count++;
}
26
Problem
 Given a file with the following contents:
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jennifer 8.0 8.0 8.0 8.0 7.5
 Consider the task of computing hours worked by each
person
 Approach:
 Break the input into lines.
 Break each line into tokens.
27
Scanner on strings
 A Scanner can tokenize a String, such as a line of a file.
Scanner <name> = new Scanner(<String>);
 Example:
String text = "1.4 3.2 hello 9 27.5";
Scanner scan = new Scanner(text);
System.out.println(scan.next()); // 1.4
System.out.println(scan.next()); // 3.2
System.out.println(scan.next()); // hello
28
Tokenize an entire file
 We can use string Scanner(s) to tokenize each line of
a file:
Scanner scan = new Scanner(new File(<file name));
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner lineScan = new Scanner(line);
<process this line...>;
}
29
Example
 Example: Count the tokens on each line of a file.
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
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);
}
31
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: " + fmt.format(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.
32

More Related Content

Similar to ExtraFileIO.pptx

Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
theodorelove43763
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
WebStackAcademy
 
srgoc
srgocsrgoc
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Write a program that will count the number of characters- words- and l.docx
Write a program that will count the number of characters- words- and l.docxWrite a program that will count the number of characters- words- and l.docx
Write a program that will count the number of characters- words- and l.docx
lez31palka
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
atulkapoor33
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
BG Java EE Course
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
Gaurav Singh
 
Java practical
Java practicalJava practical
Java practical
william otto
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
Nico Ludwig
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
f3apparelsonline
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Lab4
Lab4Lab4

Similar to ExtraFileIO.pptx (20)

Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
srgoc
srgocsrgoc
srgoc
 
15. text files
15. text files15. text files
15. text files
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Write a program that will count the number of characters- words- and l.docx
Write a program that will count the number of characters- words- and l.docxWrite a program that will count the number of characters- words- and l.docx
Write a program that will count the number of characters- words- and l.docx
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Java practical
Java practicalJava practical
Java practical
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
 
Lab4
Lab4Lab4
Lab4
 

Recently uploaded

一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
enxupq
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
ewymefz
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
oz8q3jxlp
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
axoqas
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
NABLAS株式会社
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
TravisMalana
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
ahzuo
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
balafet
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
vcaxypu
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
Subhajit Sahu
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
NABLAS株式会社
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单
ocavb
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
ewymefz
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
slg6lamcq
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
ewymefz
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
benishzehra469
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
u86oixdj
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar
 

Recently uploaded (20)

一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
 
Machine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptxMachine learning and optimization techniques for electrical drives.pptx
Machine learning and optimization techniques for electrical drives.pptx
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
 
一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单一比一原版(TWU毕业证)西三一大学毕业证成绩单
一比一原版(TWU毕业证)西三一大学毕业证成绩单
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
 
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
原版制作(Deakin毕业证书)迪肯大学毕业证学位证一模一样
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
 

ExtraFileIO.pptx

  • 1. File Input and Output TOPICS • File Input • Exception Handling • File Output
  • 2. File class in Java  Programmers refer to input/output as "I/O".  The File class represents files as objects.  The class is defined in the java.io package.  Creating a File object allows you to get information about a file on the disk.  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(); } 2
  • 3. Files  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
  • 4. Scanner reminder  The Scanner class reads input and processes strings and numbers from the user.  When constructor is called with System.in, the character stream is input typed to the console.  Instantiate Scanner by passing the input character stream to the constructor: Scanner scan = new Scanner(System.in); 4
  • 5. 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( ); 5
  • 6. Opening a file for reading  To read a file, pass a File object as a parameter when constructing a Scanner  Scanner for a file: Scanner <name> = new Scanner(new File(<filename>));  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
  • 7. File names and paths  relative path: does not specify any top-level folder, so the path is relative to the current directory:  "names.dat"  "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” 7
  • 8. 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/P4  Scanner will look for ~/workspace/P4/data/input.txt 8
  • 9. Compiler error with files  Question: Why will the following program NOT compile? import java.io.*; // for File import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) { File file = new File(“input.txt”); Scanner scan = new Scanner(file); String text = scan.next(); System.out.println(text); } }  Answer: Because of Java exception handling! 9
  • 10. Compiler error with files  Here is the compilation error that is produced: ReadFile.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner scan = new Scanner(new File("data.txt"));  The problem has to do with error reporting.  What to do when a file cannot be opened?  File may not exist, or may be protected.  Options: exit program, return error, or throw exception  Exceptions are the normal error mechanism in Java. 10
  • 11. Exceptions  exception: An object that represents a program error.  Programs with invalid logic will cause exceptions.  Examples:  dividing by zero  calling charAt on a String with an out of range index  trying to read a file that does not exist  We say that a logical error results in an exception being thrown.  It is also possible to catch (handle) an exception. 11
  • 12. Checked exceptions  checked exception: An error that must be handled by our program (otherwise it will not compile).  We must specify what our program will do to handle any potential file I/O failures.  We must either:  declare that our program will handle ("catch") the exception, or  state that we choose not to handle the exception (and we accept that the program will crash if an exception occurs) 12
  • 13. 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 <type> <name>(<params>) throws <type> { … }  When doing file open, we throw IOException. public static void main(String[] args) throws IOException { 13
  • 14. 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); } } 14
  • 15. 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. 15
  • 16. Using Scanner to read file data  Consider a file numbers.txt that contains this text: 308.2 14.9 7.4 2.8 3.9 4.7 -15.4 2.8  A Scanner views all input as a stream of characters:  308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n 16
  • 17. Consuming tokens  Each call to next, nextInt, nextDouble, etc. advances the position of the scanner to the end of the current token, skipping over any whitespace: 308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n ^ scan.nextDouble(); 308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n ^ scan.nextDouble(); 308.2n 14.9 7.4 2.8nnn3.9 4.7 -15.4n2.8n ^ 17
  • 18. First problem  Write code that reads the first 5 double values from a file and prints. 18
  • 19. 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); } } 19
  • 20. Second problem  How would we modify the program to read all the file? 20
  • 21. Second solution public static void main(String[] args) try { File file = new File(“input.txt”); Scanner scan = new Scanner(file); while (scan.hasNextDouble() { double next = scan.nextDouble(); System.out.println("number = " + next); } } catch (IOException e) { System.out.println(“Unable to open input.txt”); System.exit(-1); } } 21
  • 22. Refining the problem  Modify the program again to handle files that also contain non-numeric tokens.  The program should skip any such tokens.  For example, it should produce the same output as before when given this input file: 308.2 hello 14.9 7.4 bad stuff 2.8 3.9 4.7 oops -15.4 :-) 2.8 @#*($& 22
  • 23. Refining the program while (scan.hasNext()) { if (scan.hasNextDouble()) { double next = scan.nextDouble(); System.out.println("number = " + next); } else { // consume the bad token scan.next(); } } 23
  • 24. Reading input line-by-line  Given the following input data: 23 3.14 John Smith "Hello world" 45.2 19  The Scanner can read it line-by-line: 23t3.14 John Smitht"Hello world"ntt45.2 19n ^ scan.nextLine() 23t3.14 John Smitht"Hello world"ntt45.2 19n ^ scan.nextLine() 23t3.14 John Smitht"Hello world"ntt45.2 19n ^  The n character is consumed but not returned. 24
  • 25. File processing question  Write a program that reads a text file and adds line numbers at the beginning of each line 25
  • 26. Solution int count = 0; while (scan.hasNextLine()) { String line = scan.nextLine(); System.out.println(count + “ “ + line); count++; } 26
  • 27. Problem  Given a file with the following contents: 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jennifer 8.0 8.0 8.0 8.0 7.5  Consider the task of computing hours worked by each person  Approach:  Break the input into lines.  Break each line into tokens. 27
  • 28. Scanner on strings  A Scanner can tokenize a String, such as a line of a file. Scanner <name> = new Scanner(<String>);  Example: String text = "1.4 3.2 hello 9 27.5"; Scanner scan = new Scanner(text); System.out.println(scan.next()); // 1.4 System.out.println(scan.next()); // 3.2 System.out.println(scan.next()); // hello 28
  • 29. Tokenize an entire file  We can use string Scanner(s) to tokenize each line of a file: Scanner scan = new Scanner(new File(<file name)); while (scan.hasNextLine()) { String line = scan.nextLine(); Scanner lineScan = new Scanner(line); <process this line...>; } 29
  • 30. Example  Example: Count the tokens on each line of a file. 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 30
  • 31. 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); } 31
  • 32. 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: " + fmt.format(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. 32