21
CS 1302 – Lab 06 This lab provides an introduction to reading and writing text files. There are 6 stages to complete this lab: Stag e Title Text Reference 1 Reading Simply Formatted Data from a Text File 12.11 2 Parsing Data 12.11 3 More Parsing 12.11 4 Writing Data to a Text File 12.11 5 The File Class 12.10 6 Reading & Writing Example 12.11 To make this document easier to read, it is recommend that you turn off spell checking in Word: 1. Choose: File, Option, Proofing 2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…” Stage 1 - Reading Simply Formatted Data from a Text File In this stage you will learn how to read an arbitrary number of items with a repetitive pattern from a text file. 1. Read (no action required) a. A text file is actually a file filled with binary digits, 1’s and 0’s (which itself is an abstraction). However, the software (Word, Eclipse, etc.) that accesses a text file uses character decoding. For example, the binary stream: 01001010011000010111011001100001 Is decoded (each 8 bits) as: 8-bit Blocks 010010 10 011000 01 011101 10 011000 01 Decoded ASCII J a v a 1 ASC II De c Hex Binary 0 48 30 0011 0000 1 49 31 0011 0001 2 50 32 0011 0010 A 65 41 0100 0001 B 66 42 0100 0010 C 67 43 0100 0011 a 97 61 0110 0001 b 98 62 0110 0010 c 99 63 0110 0011

mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

  • Upload
    hahuong

  • View
    221

  • Download
    6

Embed Size (px)

Citation preview

Page 1: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

CS 1302 – Lab 06

This lab provides an introduction to reading and writing text files. There are 6 stages to complete this lab:

Stage Title Text Reference1 Reading Simply Formatted Data from a Text File 12.112 Parsing Data 12.113 More Parsing 12.114 Writing Data to a Text File 12.115 The File Class 12.106 Reading & Writing Example 12.11

To make this document easier to read, it is recommend that you turn off spell checking in Word:

1. Choose: File, Option, Proofing2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…”

Stage 1 - Reading Simply Formatted Data from a Text File

In this stage you will learn how to read an arbitrary number of items with a repetitive pattern from a text file.

1. Read (no action required) –

a. A text file is actually a file filled with binary digits, 1’s and 0’s (which itself is an abstraction). However, the software (Word, Eclipse, etc.) that accesses a text file uses character decoding. For example, the binary stream:

01001010011000010111011001100001

Is decoded (each 8 bits) as:

8-bit Blocks 01001010 01100001

01110110 01100001

Decoded ASCII Text J a v a

b. The encoding/decoding scheme shown on the right is ASCII. For example the (partial) table above on the right shows how text is encoded/decoded. For example, the ASCII letter “a” is represented in binary as: 01100001. ASCII was the standard on the internet until 2007. Now, UTF-8 is the standard. UTF-8 was designed to be backwards compatible with ASCII, so they are the same. Be default, Java reads and writes using ASCII, however you can set a parameter to use UTF-8.

c. The information above is not directly needed for this course but is useful for a general understanding. Usually (and always for this course) when we read/write information to/from a text file the decoding/encoding is done automatically.

1

ASCII Dec Hex Binary0 48 30 0011 00001 49 31 0011 00012 50 32 0011 0010… … … …A 65 41 0100 0001B 66 42 0100 0010C 67 43 0100 0011… … … …a 97 61 0110 0001b 98 62 0110 0010c 99 63 0110 0011… … … …

Page 2: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

2. Read (no action required) –

a. Consider a text file with the data shown on the right. The line numbers (1-15) are shown on the left and are not a part of the file. Each three lines represents an employee: name, salary, age.

b. To read (or write) data we first create an instance of the File class which contains the location of the file. Later in this tutorial we will look more closely at the File class. For now, we will just see how to create an instance. The File class constructor accepts a path with the location and name of the file. For example:

File inFile = new File( "src\\examples1\\employees1.txt" );

specifies that the file is named employee1.txt and it is found in the src\examples1 folder. An additional “\” is needed to delimit the single, required “\” in the path. Notice that this is a relative path. Eclipse is configured to look for a file in the src folder by default and since we will typically have our code in a package (example1 in the example above) we need to specify the full path.

c. We use the Scanner class in Java to read from a text file (just as you did to read from the keyboard) passing into its constructor a File object.

Scanner input = new Scanner( inFile );

d. To read all the employees in the file (no matter the number and assuming no data is missing) we use code like this:

while( input.hasNext() ) {String name = input.next();double salary = input.nextDouble();int age = input.nextInt();

...}input.close();

e. Of course we would want to do something with the data we have read in, perhaps count it, or add it. And other times we may need to store it in an array or ArrayList. In the example that follows in each iteration over the loop we will create an Employee object and put it into an ArrayList.

3. Setup – Do the following:

a. Establish a Workspace – Create a folder on your drive where you will put your lab or use an existing one.

b. Run Eclipse – As the program begins to run, it will ask you to navigate to the Workspace you want to use.

c. Create a Project – Create a Java project with the name, lab06_lastNameFirstInitial, e.g. lab06_gibsond.d. Create a package named read_examples.

4. Create Text File – Do the following:

a. Select the read_examples package.

2

Page 3: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

b. Choose: File, New, File

c. Verify that the “parent folder” is read_examples as shown on the right.

d. Supply the file name: employees1.txt.

e. Choose Finish.

f. Verify that you see the file in the Package Explorer as shown on the right. The file needs to be insider the read_examples package as shown on the right.

g. The file should be open. Copy the data below and paste into the file and save.

Dave44.5533Sue33.4445Sherry55.3418Mike23.4523Nicole76.3419

Note: You will probably end up with a blank line in the file (line 16). I don’t think it will affect the reading, but probably better to use backspace to delete that line.

5. Create Classes to Read and Store Data – Do the following:

a. Create a class named Employee (in the read_examples package) and replace everything in the class (except the package statement at the top) with:

public class Employee{

private String name;private double salary;private int age;

public Employee( String name, double salary, int age ){

this.name = name;this.salary = salary;this.age = age;

}

public String getName() { return name; }public double getSalary() { return salary; };public int getAge() { return age; }

3

Page 4: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

@Overridepublic String toString() {

return "Employee [name=" + name + ", salary=" + salary + ", age="+ age + "]";

}}

b. Create a class named EmployeeReader and replace everything in the class (except the package statement at the top) with:

import java.util.ArrayList;import java.util.Scanner;import java.io.File;import java.io.IOException;

public class EmployeeReader {public static void main(String[] args) {

ArrayList<Employee> employees = new ArrayList<>();

File inFile = new File( "src\\read_examples\\employees1.txt" );

try {Scanner input = new Scanner( inFile );while( input.hasNext() ) {

String name = input.next();double salary = input.nextDouble();int age = input.nextInt();employees.add(new Employee( name, salary, age ));

}input.close();

}catch( IOException e ) {

System.out.println(e);}

for( Employee e : employees )System.out.println(e);

}}

Note: File operations can throw an IOException, which is a checked exception. Thus, we must either surround file operations with try/catch as shown above or declare the exception by placing throws IOException on the end of the definition of the method doing the file operations (main in this case).

c. Run and verify the output:

Employee [name=Dave, salary=44.55, age=33]Employee [name=Sue, salary=33.44, age=45]Employee [name=Sherry, salary=55.34, age=18]Employee [name=Mike, salary=23.45, age=23]Employee [name=Nicole, salary=76.34, age=19]

6. Read (no action required) – Consider the three text files shown below. It can be a bit confusing, but the code we wrote above to read employees1.txt will read any one of these properly. We will show that next.

4

Page 5: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

7. Test other Layouts of the Data – Do the following:

a. Copy employees1.txt and give it the new name: employees2.txt.

b. Open employees2.txt and reformat so that it looks as shown in the figure above: each employee on a separate line.

c. Copy employees2.txt and give it the new name: employees2.txt.

d. Open employees3.txt and reformat so that it looks as shown in the figure above: all the employees on a single line.

e. Open EmployeeReader and change the reference to employees1.txt to employees2.txt.

File inFile = new File( "src\\read_examples\\employees2.txt" );

f. Run and verify that the output is the same as before.

g. Open EmployeeReader and change the reference to employees2.txt to employees3.txt.

h. Run and verify that the output is the same as before.

5

Page 6: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

Stage 2 - Parsing Data

In this stage we show an example of parsing data. Parsing means to read a data item, figure out what it is, and then use it to figure out what to read next.

8. (Read, no action required) – Suppose we have a file that contains integers and words in any arbitrary order as shown in the figure below:

We would like to read the entire file and put all the integers in one ArrayList and all the words in another. One way to do this is to read each token:

String token = input.next();

and use a regular expression to test if it contains all digits:

if( token.matches("\\d+") ) {

If is passes this test, then we can safely parse it as an integer:

int x = Integer.parseInt(token);

Thus, the body of the read loop will look like this (where ints and words are the ArrayLists used to store the data):

while( input.hasNext() ) {String token = input.next();if( token.matches("\\d+") ) {

int x = Integer.parseInt(token);ints.add(x);

}else {

words.add(token);}

}

9. Create Classes to Read and Store Data – Do the following:

a. Create a text file (see directions above if necessary) named: numbersAndWords.txt.

b. Copy this data into the file:

33 992 guitar 8 fire 29 344 5 hat pick rain 1 horse 18

6

Page 7: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

c. Create a class named ReadNumbersAndWords (in the read_examples package) and replace everything in the class (except the package statement at the top) with:

import java.util.ArrayList;import java.util.Scanner;import java.io.File;import java.io.IOException;

public class ReadNumbersAndWords {public static void main(String[] args) {

ArrayList<Integer> ints = new ArrayList<>();ArrayList<String> words = new ArrayList<>();File inFile = new File( "src\\read_examples\\numbersAndWords.txt" );

try {Scanner input = new Scanner( inFile );while( input.hasNext() ) {

String token = input.next();if( token.matches("\\d+") ) {

int x = Integer.parseInt(token);ints.add(x);

}else {

words.add(token);}

}input.close();

}catch( IOException e ) {

System.out.println(e);}

System.out.println(" ints: " + ints);System.out.println("words: " + words);

}}

d. Run and verify the output:

ints: [33, 992, 8, 29, 344, 5, 1, 18]words: [guitar, fire, hat, pick, rain, horse]

7

Page 8: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

Stage 3 - More Parsing

In this stage we show another example of parsing data.

10. (Read, no action required) – Suppose we have a file as shown on the right. A person (Dave) is shown on line 1 and the number of dogs he has (2). The next two lines show the two dogs. We would like to read the entire file of people where each person can have a different number of dogs. One way to do this is to read a person’s name

String name = input.next();

and then read their number of dogs

int numDogs = input.nextInt();

and then loop over the number of dogs reading each dog’s name:

for(int i=0; i<numDogs; i++){String dogName = input.next();...

}

Now, suppose we have Person and Dog classes as shown in the class diagram on the right. Then, we can build an ArrayList<Person> with code like this:

ArrayList<Person> people = new ArrayList<>();...

while( input.hasNext() ) {String name = input.next();Person p = new Person(name);int numDogs = input.nextInt();for(int i=0; i<numDogs; i++){

String dogName = input.next();Dog dog = new Dog(dogName);p.addDog(dog);

}people.add(p);

}

11. Create Classes to Read and Store Data – Do the following:

a. Create a text file (see directions above if necessary) named: peopleAndDogs.txt in the read_examples package.

8

Page 9: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

b. Copy this data into the file:

Dave 2FidoLeoRaquel 1JunoAlex 3SnoopyBarleyMoses

c. Create a class named Dog (in the read_examples package) and replace everything in the class (except the package statement at the top) with:

public class Dog {private String name;

public Dog(String name) {this.name = name;

}

public String getName() {return name;

}}

d. Create a class named Person (in the read_examples package) and replace everything in the class (except the package statement at the top) with:

import java.util.ArrayList;

public class Person {ArrayList<Dog> dogs = new ArrayList<>();private String name;

public Person(String name){this.name = name;

}

public void addDog(Dog dog) {dogs.add(dog);

}

@Overridepublic String toString(){

StringBuilder msg = new StringBuilder();msg.append("Person: " + name + " - Dogs: ");for(Dog dog : dogs)

msg.append(dog.getName() + ", ");msg.delete(msg.length()-2,msg.length());return msg.toString();

}}

9

Page 10: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

e. Create a class named ReadPeopleAndDogs (in the read_examples package) and replace everything in the class (except the package statement at the top) with:

import java.util.ArrayList;import java.util.Scanner;import java.io.File;import java.io.IOException;

public class ReadPeopleAndDogs {public static void main(String[] args) {

ArrayList<Person> people = new ArrayList<>();File inFile = new File( "src\\read_examples\\peopleAndDogs.txt" );

try {Scanner input = new Scanner( inFile );while( input.hasNext() ) {

String name = input.next();Person p = new Person(name);int numDogs = input.nextInt();for(int i=0; i<numDogs; i++){

String dogName = input.next();Dog dog = new Dog(dogName);p.addDog(dog);

}people.add(p);

}input.close();

}catch( IOException e ) {

System.out.println(e);}

for(Person p : people) {System.out.println(p);

}}

}

f. Run and verify the output:

Person: Dave - Dogs: Fido, LeoPerson: Raquel - Dogs: JunoPerson: Alex - Dogs: Snoopy, Barley, Moses

10

Page 11: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

Stage 4 - Writing Data to a Text File

In this stage we demonstrate how to write data to a text file using the PrintWriter class.

12. (Read, no action required) –

a. One way to write data to a text file is to use the PrintWriter class. It accepts a File as an argument:

File outFile = new File("src\\write_examples\\numbers.txt");PrintWriter writer = new PrintWriter( outFile );

b. Probably the three most useful (at least for our class) methods of the PrintWriter class are print(…), println(…), and printf(…) which work identically to the System.out.print(…) methods. For example, to loop over an array of integers (nums) and write them space-delimited to a text file:

for( int i=0; i<nums.length; i++ ) {writer.print( nums[i] + " " );

}

c. When we are done writing, we must close the writer: writer.close(); And, as with the Scanner class, we must try/catch (or throws…) all file manipulations.

13. Create Classes to Read and Store Data – Do the following:

a. Create a package named write_examples.

b. Create a class named WriteArray (in the write_examples package) and replace everything in the class (except the package statement at the top) with:

import java.io.File;import java.io.IOException;import java.io.PrintWriter;

public class WriteArray {

public static void main(String[] args) {int[] nums = {33, 44, 55, 66, 12, 33, 55, 66, 77, 22};

File outFile = new File( "src\\write_examples\\numbers.txt" );

try {PrintWriter writer = new PrintWriter( outFile );for( int i=0; i<nums.length; i++ ) {

writer.print( nums[i] + " " );}writer.close();System.out.println( "File written" );

}catch (IOException ioe) {

System.out.println("Problem creating file or writing");}

}}

11

Page 12: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

c. Run and verify the output in the console:

File written

d. Select the write_examples package in the Package Explorer and choose: File, Refresh (or F5) and you should see the output file, numbers.txt appear. Open it and verify the contents.

e. Find the array declaration in WriteArray and add a number to the beginning of the array.

f. Run the program and examine the contents of numbers.txt. Note that the previous file was overwritten completely. In many situations you would want to check before overwriting a file. This is easily handled with the File class as we will see later.

Stage 5 - The File Class

In this stage we demonstrate a few methods of the File class.

14. The File class has many useful methods. The following example will illustrate some of them. Do the following:

a. Create a class named FileClassTest (in the write_examples package) and replace everything in the class (except the package statement at the top) with:

import java.io.File;import java.io.IOException;

public class FileClassTest {

public static void main(String[] args) throws IOException {File inFile = new File( "src\\write_examples\\numbers.txt" );

System.out.println("File exists : " + inFile.exists());System.out.println("File size : " + inFile.length() + " bytes");System.out.println("Can be read : " + inFile.canRead());System.out.println("Can be written: " + inFile.canWrite());System.out.println("Is a directory: " + inFile.isDirectory());System.out.println("Is a file : " + inFile.isFile());System.out.println("Is hidden : " + inFile.isHidden());System.out.println("Absolute path : " + inFile.getAbsolutePath());System.out.println("Path : " + inFile.getPath());System.out.println("Parent : " + inFile.getParent());System.out.println("Name : " + inFile.getName());// Must compute the "true" pathString absPath = inFile.getAbsolutePath();int begOfFileName = absPath.lastIndexOf(inFile.getName());String truePath = absPath.substring(0,begOfFileName);System.out.println("True path : " + truePath);

System.out.println("Last modified : " + new java.util.Date(inFile.lastModified()));

}}

12

Page 13: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

b. Run and verify the output. As long as numbers.txt is still in your package you will see information about that file.

c. Change the filename to one that doesn’t exist and re-run and verify the output.

d. Change the filename back to the original (number.txt), re-run and verify that it runs as expected.

15. Read (no action required) – A slightly more robust template for reading, where we detect whether the file exists before attempting to read might look like this:

File inFile = new File( "src\\write_examples\\numbers2.txt" );

if( inFile.exists()) {try {

Scanner input = new Scanner( inFile );while( input.hasNext() ) {

// Read a token...}input.close();

}catch( IOException e ) {

System.out.println(e);}

}else {

System.out.println("File doesn't exist: " + inFile.getAbsolutePath());System.out.println("Program terminated");

}

To allow the user to supply a new file name would be slightly more involved. A loop would need to be added that continued until a successful file name was supplied or the user indicated that the program should stop. Similarly, before writing, we could detect if the file already exists and ask the user if they want to overwrite or supply a new name.

13

Page 14: mypages.valdosta.edumypages.valdosta.edu/dgibson/courses/cs1302/labs/cs1…  · Web viewon the end of the definition of the method doing the file operations (main . in this case)

Stage 6 - Reading & Writing Example

In this stage we illustrate both reading and writing together. The scenario is that we have a file of integers which we want to read and then write the integers that are larger than 99 to another file.

16. Do the following:

a. Create a new text file named numbers2.txt and paste these numbers into the file:

8 47 333 555 1 888 9 4 2 222

b. Create a class named ReadWriteIntegers (in the write_examples package) and replace everything in the class (except the package statement at the top) with:

import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Scanner;

public class ReadWriteIntegers {

public static void main(String[] args) {File inFile = new File( "src\\write_examples\\numbers2.txt" );File outFile = new File( "src\\write_examples\\bigNumbers.txt" );

try {Scanner input = new Scanner(inFile);PrintWriter writer = new PrintWriter(outFile);while( input.hasNext() ) {

int val = input.nextInt();if(val > 99) {

writer.print(val + " ");}

}input.close();writer.close();System.out.println("Program completed successfully");

}catch( IOException e ) {

System.out.println(e);}

}}

c. Run and verify the console output:

Program completed successfully

d. Select the write_examples package in the Package Explorer and choose: File, Refresh (or F5) and you should see the output file, bigNumbers.txt appear. Open it and verify the contents.

You are done!

14