Section 11.8. Using File Data in Programs


[Page 548 (continued)]

11.8. Using File Data in Programs

This chapter's examples have provided explicit details for several ways of writing data to files and reading data from files. In actual programs, deciding if and how files might be useful in the program are worked out as part of the design process. Choosing between text files, binary files, and reading and writing objects is part of this process.

To illustrate how we can apply what we have learned about file I/O, let's modify the WordGuess class (listed in Fig. 8.27) so that it reads a list of possible words for players to guess from a file. The Chapter 8 version of the class contains a method, getSecret Word(), which uses a switch statement to randomly choose and return a word from a fixed list of 10 words. Reading the words from a text file would allow a user to modify the list of possible words by adding or changing words without needing to recompile the program.

Modifying WordGuess


We will modify the WordGuess class in three ways:

1.

Add two new instance variables, an array of type String and a variable to store the size of the array;

2.

Add code at the beginning of the class's constructor to read words from the file and store them in the array;

3.

Rewrite the getSecretWord() method so that it randomly chooses a word from the array.

Let us first choose descriptive names for declaring the two new instance variables:

private String[] wordArray; private int arraySize; 


New instance variables



[Page 549]

It will be useful to store the number of words in the file in its first line so that this information can be used to allocate memory for the array. For example, assume that the text file will be named secretwords.txt, will be located in the same directory as the WordGuess class, will have the same number of words in the file as its first line, and will have a single word per line after that. Thus, a small file might look like:

3 STREAMS CONDUIT DIALOGS 


Format for the text file


We can use the body of the readTextFile() method of the TextIO class as a model for the Java code that needs to be added to the WordGuess constructor. Pseudocode for this code will look like:

Use file name to open a  BufferedReader stream Read first line and convert to an integer Store the integer as the size of the array Allocate memory for the array Read second line of file While a word is read    Store the word in the next array element    Read next line of file Close the BufferedReader stream 


Code to add to constructor


When this pseudocode is translated into Java and inserted into a try-catch statement, we get the code fragment in Figure 11.31.

Figure 11.31. Code added at beginning of the WordGuess constructor.

try{     FileReader fr = new FileReader("secretwords.txt");     BufferedReader inStream = new BufferedReader(fr);     String line = inStream.readLine();     arraySize = Integer.parseInt(line);     wordArray = new String[arraySize];     line = inStream.readLine();     int k = 0;     while((line != null) && (k < arraySize)){         wordArray[k] = line;         line = inStream.readLine();         k++;     } // while     inStream.close(); } catch(FileNotFoundException e){     e.printStackTrace(); } catch(IOException e){     e.printStackTrace(); } // catch 


[Page 550]

The new getSecretWord() method merely needs to generate a random array index and return the corresponding array element:

private String getSecretWord(){     int num = (int)(Math.random()*arraySize);     return wordArray[num]; } // getSecretWord() 


New code for getSecretWord


Databases and Personal Privacy

During a typical day we all come in contact with lots of electronic databases that store information about us. If you use a supermarket discount card, every purchase you make is logged against your name in the supermarket's database. When you use your bank card at the ATM machine, your financial transaction is logged against your account. When you charge gasoline or buy dinner, those transactions are logged against your credit card account. If you visit the doctor or dentist, a detailed record of your visit is transmitted to your medical insurance company's database. If you receive a college loan, detailed financial information about you is entered into several different credit service bureaus. And so on.

Should we be worried about how this information is used? Many privacy advocates say yes. With the computerization of medical records, phone records, financial transactions, driving records, and many other records, there is an enormous amount of personal information held in databases. At the same time, there are pressures from many sources for access to this information. Law-enforcement agencies want to use this information to monitor individuals. Corporations want to use it to help them market their products. Political organizations want to use it to help them market their candidates.

Recently there has been pressure from government and industry in the United States to use the social security number (SSN) as a unique identifier. Such an identifier would make it easy to match personal information across different databases. Right now, the only thing your bank records, medical records, and supermarket records may have in common is your name, which is not a unique identifier. If all online databases were based on your SSN, it would be much simpler to create a complete profile. While this might improve services and reduce fraud and crime, it might also pose a significant threat to our privacy.

Online databases serve many useful purposes. They help fight crime and reduce the cost of doing business. They help improve government and commercial services on which we have come to depend. On the other hand, databases can be and have been misused. They can be used by unauthorized individuals or agencies or in unauthorized ways. When they contain inaccurate information, they can cause personal inconvenience or even harm.

A number of organizations have sprung up to address the privacy issues raised by online databases. If you're interested in learning more about this issue, a good place to start would be the Web site maintained by the Electronic Privacy Information Center (EPIC) at

http://www.epic.org/



[Page 551]

The only other modification needed to complete the new WordGuess class is to add an initial import java.io.*; statement so that the file IO classes can be accessed.

The earlier examples in this chapter can be used as models to enhance numerous practical applications. GUI applications that involve a user's choice to load data from a file or save data in a file should make use of the JFileChooser dialogs to initiate the file operations.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net