se-1020 dr. mark l. hornick 1 file input and output

20
SE-1020 Dr. Mark L. Hornick 1 File Input and Output

Upload: griffin-jennings

Post on 02-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

1

File Input and Output

Page 2: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

2

A program typically reads the data it manipulates from a file, or writes the data it has manipulated to a file

File output is the action of writing data to a file.

File input is the action of reading data from a file.

Page 3: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

CS-1020Dr. Mark L. Hornick

3

The File class from java.io…provides an abstraction of a physical file (or file

directory) on a local (or network) filesystem

File inFile = new File(“sample.dat”);

File inFile = new File(“C:/SamplePrograms/test.dat”);

Opens (associates) the file sample.dat in the current directory.

Opens (associates) the file sample.dat in the current directory.

Opens the file test.dat in the directory C:\SamplePrograms using the universal file separator / and providing the full pathname.

Opens the file test.dat in the directory C:\SamplePrograms using the universal file separator / and providing the full pathname.

Page 4: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

CS-1020Dr. Mark L. Hornick

4

Some File methods and their functions

method function

canRead Tests whether the application can read the file

canWrite Tests whether the application can modify the file

delete Deletes the file or directory

exists Tests whether the file or directory exists

isDirectory Tests whether the file is a directory

isFile Tests whether the file is a normal file

isHidden Tests whether the file is a hidden file

length Returns the length of the file (in bytes)

listReturns an array of abstract pathnames denoting the files in the directory

renameTo Renames the file

Page 5: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

CS-1020Dr. Mark L. Hornick

5

File method examples

if ( inFile.exists( ) ) {

if ( inFile.isFile() ) {

File directory = new File("C:/JavaPrograms/Ch12");

// list() returns an array of StringsString filename[] = directory.list();

for (int i = 0; i < filename.length; i++) {System.out.println(filename[i]);

}

To see if inFile is associated to a real file correctly.

To see if inFile is associated to a real file correctly.

To see if inFile is associated to a file or not. If false, it is a directory.

To see if inFile is associated to a file or not. If false, it is a directory.

List the name of all files in the directory C:\JavaProjects\Ch12

List the name of all files in the directory C:\JavaProjects\Ch12

Page 6: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

CS-1020Dr. Mark L. Hornick

6

Note that there are no read() or write() methods in the File class

To read data from or write data to a file, a Java stream object must be created and attached to the file A stream is a sequence of data items

Page 7: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

7

First - The Big Question:

How should we store data in a file?

Page 8: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

8

Let’s say we have numeric (e.g. integer) data to be stored.

How can integer data be stored??? Integers (in Java) occupy 4 bytes (32 bits)…

…so we can store any integer value as 4 raw bytes of data:-2000000000-100000250000450000000

Page 9: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

9

Here’s an example of a file containing raw integer binary data when viewed with Notepad

Q: What do these characters represent??

Page 10: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

10

Instead of storing primitive data values as binary data in a file, they can be converted to their character representation and stored as string data This is known as text file IO

This allows the file content to be viewed using any text editor

To output data (regardless of datatype) as a text to file, a PrintWriter object is used

Page 11: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

11

PrintWriter is a class for outputting data in text format

The ‘out’ field in System.out is actually a PrintWriter object:class System { // Java’s System class

public static PrintWriter out;

} The PrintWriter class contains the print() and println()

methods The System class associates a PrintWriter object named

out with the console

Page 12: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

12

To use PrintWriter for creating file output:

PrintWriter pw = new PrintWriter( file ); The file parameter is a String containing the name

of a file to be created If file=“output.txt”, the file is created in the current

directory Otherwise, a full directory path can be specified

“C:\\temp\\output.txt” creates the file in C:\temp You can use / instead of \\ in the file path specification:

“C:/temp/output.txt”

Note: we’re using the simplest of 8 different PrintWriter constructors here;this constructor accepts a single String argument specifying the filename.

Page 13: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

13

Any existing file with the name specified as the PrintWriter argument will be overwritten

However, the specified file must be creatable! A NoSuchFileException is thrown if

There is not enough disk space The file path specified does not exist Is marked “readonly” If the file belongs to some other user (a security

violation) and you don’t have permission to access it

Page 14: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

14

To write using the PrintWriter:

pw.println(“This string will go in the file”); Use the print() and println() methods just as you

would when using System.out

Page 15: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

To append to an existing file, another version of the overloaded PrintWriter constructor is used

This version of PrintWriter accepts a single argument – a reference to a FileWriter object FileWriter is a “helper” class that PrintWriter uses

to append characters to an existing file.

//create a FileWriter, true specifies append

FileWriter fw = new FileWriter( file, true );

PrintWriter pw = new PrintWriter( fw ); pw.println(“This string will go at the end of

the file”); SE-1020

Dr. Mark L. Hornick15

Page 16: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

16

Conversely, for reading data stored as text in a file, we use the familiar Scanner class: Recall the use of the Scanner class in conjunction

with System.in:

Scanner reader = new Scanner( System.in );int i = reader.nextInt();

Page 17: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

17

To use the Scanner class for reading text data from a file, use the “helper” class FileReaderString file = “output.txt”;

FileReader fr = new FileReader(filename);

Scanner reader = new Scanner( fr ); The filename parameter is a String containing the name

of a file to be read The fr parameter is a FileReader object that is

associated with the physical file on the filesystem. FileNotFoundException is thrown if the specified file does not

exist.

Don’t confuse creating a FileReader object with creating an actual physical file on disk!!!

Page 18: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

18

The default behavior for next() is to read from the input stream until whitespace is encountered… Scanner reader = new Scanner( fr );

String s = reader.next(); // read next String “token”int i = reader.nextInt(); // try to read an int...

Whitespace is any non-printing character Newline Tab Space

The useDelimiter() method can be invoked on a Scanner to change the default scanning behavior: reader.useDelimiter(“,”); // scan until comma

reader.useDelimiter(“[,;\\s]+”); // scan until one or more occurrences of comma, semicolon, or whitespace (tab, return, linefeed, formfeed)

Page 19: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

19

Q: What do these characters represent??

Page 20: SE-1020 Dr. Mark L. Hornick 1 File Input and Output

SE-1020Dr. Mark L. Hornick

20

ASCII Encoding of characters