0% found this document useful (0 votes)
34 views

INFO 6066 - I0 Reading Files and Writing To Files

The document discusses file paths, absolute vs relative paths, the File class, creating directories and files using File class methods, exception handling when working with files, and using a Scanner object to read text from files.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

INFO 6066 - I0 Reading Files and Writing To Files

The document discusses file paths, absolute vs relative paths, the File class, creating directories and files using File class methods, exception handling when working with files, and using a Scanner object to read text from files.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Software and Information Systems Testing

INFO 6066

Reading and Writing Text Files

1 INFO 6066
Software and Information Systems Testing

Concept: What is a “Path” ?


• A path is a string argument that indicates the location of a
folder (directory) or a file in your computer’s file system.
• Example: “C:\\Temp2” is a path to a folder(directory) on
drive ‘C’
• Example: “C:\\Temp2\\notes.txt” is a path to a file within a
folder.
• NOTE: in the Windows OS, we use the back slash as the
separator, but this is also the escape character in Java, so we
have to double the back slash character, as shown above.
• However, in the Unix OS, the file separator character is the
forward slash, so it would look like this:
“C:/Temp2/notes.txt”.
• You can actually use either style no matter what OS you are
using, because the JVM knows what OS it is running on, and
it will automatically adjust the path string to work on the OS .

2 INFO 6066
Software and Information Systems Testing

Absolute vs Relative Paths


• Any path string that begins with a drive letter or root prefix is
known as an ABSOLUTE path (T!), i.e: “C:\\Temp2\\
notes.txt”
• If the path string does not have a drive letter prefix, then the
path is a RELATIVE path. (T!)
• Java will interpret a relative path as being RELATIVE TO THE
CURRENT DIRECTORY in which your Java program is located.
• Example:
String myFile = “output.txt”;
• This is a RELATIVE path, a, and if you put this inside your
Eclipse project file, it would be relative to what ever directory
your Java project was located in, like this:
C:\MyEclipseWorkspace\FileExamplesProject\output.txt

3 INFO 6066
Software and Information Systems Testing

The File class


• A File class object in Java is best described as an abstract
representation of file and path names. (T)
• It is like a wrapper class for file names.
• Its exists( ) method can be used to determine if a specified path
leads to an actual directory or a file on the disk.
• IMPORTANT NOTE: Creating a File object DOES NOT create a
corresponding file folder on your hard drive. (T!)
• Constructor takes a string arg representing a path, i.e.
File myFolder = new File(“C:/temp2”); //using UNIX style here
• NOTE: No folder is created on the disk when this object is
instantiated BUT…we could later actually create the directories on
the disk by using methods such as mkdir() and mkdirs()
• We can also create an actual empty file using createNewFile() IF
THE FOLDERS in the path have been have been created first.

4 INFO 6066
Software and Information Systems Testing

File class cont’d


• Note on using createNewFile() method to create an empty file
• To work properly, the directory that holds the file has to be
created first. If the ‘temp34’ folder does not yet exist on the disk,
then doing the following will result in a “File Not Found”
exception.
• File fileOne = new File(“C:/temp34/myFile.txt”);
fileOne.createNewFile(); //throws FileNotFoundException
• Now, calling fileOne.mkdirs() with the above argument string
causes a problem because it creates a sub-directory named
myFile.txt inside the folder temp34, not the empty file, which is
not what we want.
• So, how can we create the folder first without having the file
name interpreted as another sub-folder?

5 INFO 6066
Software and Information Systems Testing

Using getParentFile()
• There is a method of the File object called getParentFile() which will
read the parent element or elements of the path so that we can
create them first using the mkdirs() method.
• Once this is done then we can call createNewFile() to create the
empty file

• Here’s how we can do it by using a “daisy chain” method call:

File fileOne = new File(“C:/temp34/myFile.txt”);


fileOne.getParentFile().mkdirs(); //this builds the temp34 folder
//now call createNewFile()
fileOne.createNewFile(); //creates the empty .txt file in temp 34

6 INFO 6066
Software and Information Systems Testing

Exception Handling With Files


• Exceptions are objects that are created by the Java Virtual Machine
to signal that something has gone wrong in your program.
• We say an exception “is thrown” when it is created by the JVM.
• Examples: if your loop tries to read past the end of an array in
Java, then the JVM will “throw” the
“ArrayIndexOutOfBoundsException”.
• We can prevent this exception by using “ i < array.length ;” in our
for loop continuation condition.
• Another commonly seen exception is “ArithmeticException” if your
code tries to do a division by zero operation.
• This type of exception can be prevented by using good data
validation procedures, where we check that the value of the divisor
is not zero before proceeding with the division operation.
• Another type of exception is “FileNotFoundException”, which will
be “thrown” if the JVM cannot find the file that you specified in a
path.

7 INFO 6066
Software and Information Systems Testing

Handling Exceptions:
Approach #1: “CONFESS” using throws
• If your code could possibly throw a CHECKED EXCEPTION such as
FileNotFoundException, then you must “confess” to the compiler that you
know that your code could possibly do this.
• The “confession” is done using a throws clause on the method that contains
the offending code.
• Example: in your main method you are trying to create a Scanner object
using a File object as the argument,. You need to add the throws clause to
your main method declaration like this:

public static void main(String[]args) throws FileNotFoundException


{
File inputFile = new File(“C:\\temp2\\”customers.txt”;
Scanner fileReader = new Scanner(inputFile);
}

8 INFO 6066
Software and Information Systems Testing

Confessing, cont’d
• By adding the throws clause to the method, you are
letting the compiler know that “yes, this could cause a
checked exception if the file is not found, and I am
willing to let my program crash if this occurs”.

• By confessing, the java compiler will allow your code


to compile, and if the file is not found during runtime,
then the JVM will throw the exception and your
program will crash.

• IMPORTANT: confessing using a throws clause will let


your program compile properly, but it gives no
protection if the exception is actually thrown. Your
program will crash. (T!)
9 INFO 6066
Software and Information Systems Testing

Handling Exceptions:
Approach #2: Using try-catch blocks
• A second way of handling exceptions (and the more effective way) is to
put the code that could cause the exception inside a “try” block.
• Immediately following the try block, you write a “catch” block and specify
what type of exception the catch block will “handle”, and provide a formal
parameter variable to hold the exception object when it is thrown.
• Example:
try
{
//some code that could throw a FileNotFoundException
}
catch(FileNotFoundException ex) // ‘ex’ is the formal parameter
{
//usually here we print the error message held by the object
// and the stack trace, which shows the line where the exception was
// thrown
}

10 INFO 6066
Software and Information Systems Testing

Actual catch block might look like this:

• catch(FileNotFoundException ex) // ‘ex’ is the formal parameter


{
// print the error message held by the object
System.out.println(“Exception caught, message is “ +
ex. printMessage() );
//print the stack trace
ex.printStackTrace();
} // end catch
• Each exception object has a data member of type String that
contains a short message describing what happened.
• IMPORTANT: biggest benefit of the try-catch is that after the
exception is caught by your catch block, your program keeps
running! It does not crash.

11 INFO 6066
Software and Information Systems Testing

Reading Text From an Existing File Using


a Scanner Object (text p318)
• We’ve used the Scanner object to read text from the keyboard.
• A Scanner object can also be used to read text from a file on a drive.
• When we create the Scanner, we have to specify the PATH to the file so
that the Scanner object knows where to look for the file.
• Example: suppose we’ve already created a file in Notepad with some
text in it called “message.txt”. We’ve saved this file in the project folder
of our current Eclipse project. i.e C:\MyEclipseWorkspace\
FileExamplesProject\message.txt
• To create a Scanner object to read this file, we first create a File object
to represent its path, and then we pass the File object to the
constructor method of the Scanner object:
// remember to “confess” or “play catch”
File inputFile = new File(“message.txt”); //RELATIVE path used here…
Scanner fileReader = new Scanner(inputFile);

12 INFO 6066
Software and Information Systems Testing

Reading Text, cont’d


 Suppose the text file contains this: ‘What hath God wrought?’
 To read the words from the file, we can use the .next() method in a loop:
while(fileReader.hasNext() )
{
String word = fileReader.next();
System.out.println(word);
}
 The System.out.println() will print out each word on its own line:
What
hath
God
wrought?
 The next() method returns any sequence of characters that is not white
space, such as a space character. WHITE SPACE IS CONSUMED, or
removed from the input text by the next() method (T!)

13 INFO 6066
Software and Information Systems Testing

Reading whole lines…


• If your file contains multiple lines of text then each line
will be terminated with the EOL character (return key).
• Suppose the second line in the file reads:
“First telegraph message sent in USA, 1844.”
• You can use the hasNextLine() and nextLine() methods
to read each line:
while(fileReader.hasNextLine() )
{
String line = fileReader.nextLine();
System.out.println(line);
}
• Your output would be:
What hath God wrought?
First telegraph message sent in USA, 1844.

14 INFO 6066
Software and Information Systems Testing

CONCEPT: the DELIMITER and Regular


Expressions for filtering text.
• The Scanner object has a method called useDelimiter() that allows you to
set a kind of filter that will only allow certain characters to pass through.
• CONCEPT: A delimiter is a block of character(s) that separates words. WE
DO NOT PRINT OUT THE DELIMITER character(s)
• It takes as an argument something called a regular expression, which is a
pattern of a set of character(s) inside a set of square brackets that it
either looks for or ignores, depending on how you set it up.
• Example: the regular expression [0-9]+ would be a delimiter that says
“interpret any block of one or more digits as a delimiter and do not print it
to the screen”.
• Example 2: in the regular expression[^0-9]+, the “^” caret symbol would
mean “DO NOT include any digits in the delimiter” , but ALL OTHER
CHARACTERS would be considered to be part of the delimiter, so they
would not be printed.

15 INFO 6066
Software and Information Systems Testing

Using A Delimiter to read single


characters
• You can read a file one character at a time by setting the
delimiter character to an empty string “”. This basically means
there is no character that will be a delimiter and we will therefore
look at each character in the file.
• Now we can use the next() method and not worry about it
CONSUMING white space characters such as space, newline, or
tab characters.
• Suppose you want to analyze the characters in a file to see how
many are digits, letters, upper case and lower case, or white
space.
• There are several methods of the Character class that will return
Boolean true or false: isDigit(), isLetter(), isUpperCase(),
isLowerCase(), isLetterOrDigit(), and isWhiteSpace().

16 INFO 6066
Software and Information Systems Testing

Writing to a Text File


• To write text to the screen, we use System.out.print().
• System.out is known as the standard output stream ,and it
is actually an object of the PrintStream class.
• To write text to a file on disk, we can use an object of the
class called PrintWriter.
• One way to create a PrintWriter object is to call its
constructor and pass it a file name: File myFile = new
File(“output.txt”);
Printwriter writer = new PrintWriter(myFile);
• The above code will create a file called “output.txt” in your
current Eclipse project directory.
• You then can then use the print(), println(), printf() or
write() methods to direct text to the file.

17 INFO 6066
Software and Information Systems Testing

IO Summary
• We’ve just scratched the surface of doing file input/output
here.
• We’ve dealt just with text files, in which the characters are
encoded using the Unicode coding scheme, so the bytes are
stored as characters.
• You can also read and write raw bytes to binary files, such
as .gif or .jpeg files using other classes from the Java API such
as FileInputStream and FileOutputStream, or
BufferedInputStream and BufferedOutputStream.
• There is also an updated Java library called the java.nio
package ( the ‘n’ stands for ‘new’) which provides more classes
with more capabilities for moving data between devices.

18 INFO 6066
Software and Information Systems Testing

Homework
9.1 Output and input streams
9.2 Output formatting
9.3 Streams using Strings
9.4 File input
9.5 File output

19 INFO 6066

You might also like