Topic 10 - Files and Input Output
Topic 10 - Files and Input Output
Files Input/Output
Liang, Introduction to Java Programming, Eleventh Edition (2018), Pearson Education Ltd
2 Objectives
4
5 Problem: Explore File Properties
• Objective: Write a program that demonstrates how to create files
in a platform-independent way and use the methods in the File
class to obtain their properties.
• The following figures show a sample run of the program on
Windows and on Unix.
TestFileClass
6 Text I/O
A File object encapsulates the properties of a file or a path, but
does not contain the methods for reading/writing data from/to a
file.
In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
The objects contain the methods for reading/writing data
from/to a file. This section introduces how to read/write strings
and numeric values from/to a text file using the Scanner and
PrintWriter classes.
7 Writing Data Using PrintWriter
WriteData
8 Try-with-resources
WriteDataWithAutoClose
9 Reading Data Using Scanner
ReadData
10 Problem: Replacing Text
Write a class named ReplaceText that replaces a string in a text file with
a new string.
The filename and strings are passed as command-line arguments as
follows:
java ReplaceText sourceFile targetFile oldString newString
For example, invoking
java ReplaceText FormatString.java t.txt StringBuilder StringBuffer
replaces all the occurrences of StringBuilder by StringBuffer in
FormatString.java and saves the new file in t.txt.
ReplaceText
11 Reading Data from the Web
Just like you can read data from a file on your computer,
you can read data from a file on the Web.
12 Reading Data from the Web
ReadFileFromURL
13 Case Study: Web Crawler
This case study develops a program that travels the Web by following hyperlinks.
14 Case Study: Web Crawler
WebCrawler
16
END of slides