Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Calvin College, 2009 1 All our knowledge brings us nearer to our ignorance, All our ignorance brings us nearer to death, But nearness to death, no nearer.

Similar presentations


Presentation on theme: "© Calvin College, 2009 1 All our knowledge brings us nearer to our ignorance, All our ignorance brings us nearer to death, But nearness to death, no nearer."— Presentation transcript:

1 © Calvin College, All our knowledge brings us nearer to our ignorance, All our ignorance brings us nearer to death, But nearness to death, no nearer to God. Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information? The cycles of Heaven in twenty centuries Bring us farther from God and nearer to the Dust. - T. S. Eliot, Choruses From ‘The Rock’, Selected Poems (New York: Harcourt, Brace & World, 1964), p. 107.

2 © Calvin College, File Input & Output ● Example Example ● Streams: Streams – Input Streams Input Streams – Output Streams Output Streams – Buffering Buffering – Applications Applications ● Database Management Systems Database Management Systems ● Privacy Privacy

3 © Calvin College, Example: Analysis ● We’d like to modify the guessing game so that drills students on Chinese Characters. ● A sketch of a solution achieving this goal is shown here. User’s guess… Give up Some hint goes here (maybe an image and/or audio)…

4 © Calvin College, Example: Design ● The design includes the following classes:

5 © Calvin College, Iteration 0 ● Analysis ● Design ● Implementation ● Test

6 © Calvin College, Limitations of Hard-Coding Data ● Our initial iteration assumes that: – we can code the data directly in the program; – the data never (or rarely) changes; – people who change data know how to program. ● This approach does not scale well to real data-based applications.

7 © Calvin College, Input & Output Streams ● Input and output in Java is accomplished using stream classes: Program Input Stream Output Stream Program

8 © Calvin College, Java Streams ● Simple I/O uses predefined streams: – System.in – System.out – System.err ● Create file streams using: – File – Scanner – PrintWriter

9 © Calvin College, File ● The File class models a system- independent view of a file comprising: – Filename; – Directory pathname: Relative; Absolute. ● Patterns: new File(pathAndFilenameString) new File(pathnameString, filenameString)

10 © Calvin College, Scanner ● The Scanner class can scan: – Keyboard input stream; – File; – String. ● Pattern: new Scanner(inputStreamOrFileOrString) ● The API includes these methods: – next() nextInt() nextLine()... – hasNext() hasNextInt() hasNextLine()... – close()

11 © Calvin College, Iteration 1 ● Analysis ● Design ● Implementation ● Test

12 © Calvin College, 2009 Example: File Input 12 Given: the data filename and path Algorithm: Open a read stream/scanner to the given file. While the file has more tokens: Read the token. Process the token. Close the file stream/scanner. Scanner fileIn = new Scanner(new File(path, filename)); List scores = new ArrayList (); while (fileIn.hasNext()) scores.add(fileIn.nextInt()); fileIn.close(); System.out.println(scores);

13 © Calvin College, public static double computeAverage( List values) { int sum = 0; for (int i = 0; i < values.size(); i++) sum += values.get(i); return sum / values.size(); } public static double computeVariance( List values, double average) { int sum = 0; for (int i = 0; i < values.size(); i++) sum += Math.pow(values.get(i) - average, 2); return Math.sqrt(sum / values.size()); } double average = computeAverage(scores); System.out.printf("average: %5.2f%n", average); System.out.printf("std dev: %5.2f%n", computeVariance(scores, average));

14 © Calvin College, Iteration 2 ● Analysis ● Design ● Implementation ● Test

15 © Calvin College, 2009 Example: Record Input 15 Given: the data filename and path Algorithm: Open a read stream/scanner to the given file. While the file has more lines: Read the line. Process the fixed and variant tokens. Close the file stream/scanner. Scanner fileIn = new Scanner(new File(path, filename)); List soldiers = new ArrayList (); while (fileIn.hasNextLine()) soldiers.add(new Soldier(fileIn.nextLine())); fileIn.close(); for (int i = 0; i < soldiers.size(); i++) System.out.println(soldiers.get(i));

16 © Calvin College, 2009 Example: Record Input (cont.) 16 public class Soldier { private String myName, myRank, mySerialNumber; private List myNickNames; public Soldier(String line) { Scanner scanner = new Scanner(line); myName = scanner.next(); myRank = scanner.next(); mySerialNumber = scanner.next(); myNickNames = new ArrayList (); while (scanner.hasNext()) { myNickNames.add(scanner.next()); } scanner.close(); } // other code... }

17 © Calvin College, // header information here... public class CharacterDrillController extends JFrame implements ActionListener { private final static String DATA_PATH = "src/c11files/characterdrill/data/"; private CharacterDrillPanel drillPanel; private JLabel hintLabel; private JTextField guessField; private JButton giveupButton; private CharacterDrill0 drill; public CharacterDrillController() throws URISyntaxException, FileNotFoundException { super("Character Character Drill"); setDefaultCloseOperation(EXIT_ON_CLOSE); Font font = new Font("Arial Unicode MS", 0, 24); drill = new CharacterDrill2(DATA_PATH + "characters2.txt"); hintLabel = new JLabel(); hintLabel.setFont(font); add(hintLabel, BorderLayout.CENTER); // GUI definitions here... hintLabel.setText(drill.getHintText()); drillPanel = new CharacterDrillPanel(); drillPanel.init(); add(drillPanel, BorderLayout.NORTH); drillPanel.playPronunciation(); initializeDrillPanel(); public void actionPerformed(ActionEvent event) { String actionCommand = event.getActionCommand(); try { if (actionCommand.equalsIgnoreCase("Guess")) { if (drill.guess(guessField.getText())) { drill.reset(); hintLabel.setText("Right! " + drill.getHintText()); initializeDrill(); } else { hintLabel.setText("Guess again - " + drill.getHintText()); } } else if (actionCommand.equalsIgnoreCase("Give Up")) { String answer = drill.getAnswer(); drill.reset(); hintLabel.setText("Answer: " + answer + " - Next: " + drill.getHintText()); initializeDrill(); } guessField.setText(""); } catch (URISyntaxException e) { // This should never happen... e.printStackTrace(); } private void initializeDrill() throws URISyntaxException { drillPanel.setImage(drill.getHintImageFilename()); drillPanel.setPronunciation(drill.getHintPronunciationFilename()); drillPanel.playPronunciation(); } //meain() method here... }

18 © Calvin College, // header here... public class CharacterDrill2 { private List myCharacters; private int myAnswerIndex, myHintCount; private Random myRandom; public CharacterDrill2(String path, String filename) throws Exception { myCharacters = loadCharacters(path, filename); myRandom = new Random(); reset(); } public void reset() { myAnswerIndex = myRandom.nextInt(myCharacters.size()); myHintCount = 0; } private List loadCharacters(String path, String filename) throws Exception { Scanner fileIn = new Scanner(new File(path, filename)); List result = new ArrayList (); Character character; String sentence; while (fileIn.hasNextLine()) { result.add(new Character(fileIn.nextLine())); } fileIn.close(); return result; } public String getHintText() { myHintCount++; switch (myHintCount) { case 1: return "Translate the character shown above."; case 2: return "PinYin: " + myCharacters.get(myAnswerIndex).getPinyin(); case 3: return "Example: " + myCharacters.get(myAnswerIndex).getSentence(); default: return "No more hints..."; } public String getHintImageFilename() { return myCharacters.get(myAnswerIndex).getImageFilename(); } public String getHintPronunciationFilename() { return myCharacters.get(myAnswerIndex).getPronunciationFilename(); } // other accessors/mutators here... }

19 © Calvin College, // header here... public class Character { private String myEnglishTranslation, myPinyin, myImageFilename, myPronunciation, mySentence; public Character(String line) throws Exception { Scanner scanner = new Scanner(line); myEnglishTranslation = scanner.next(); myPinyin = scanner.next(); myImageFilename = scanner.next(); myPronunciationFilename = scanner.next(); mySentence = ""; while (scanner.hasNext()) { mySentence += encodeChinese(scanner.next()); } public String getSentence() { if (mySentence.equals("")) { return "no sentence available..."; } else { return mySentence; } // Other accessors/mutators/utilities here... } // header here... public class CharacterDrillTest public void goodFileTest() { try { CharacterDrill2 drill = new CharacterDrill2("src/c11files/characterdrill/data/", "good.txt", 0); assertEquals("Translate the character shown above.", drill.getHintText()); // test other hints... } catch (Exception e) { fail("threw error on good file..."); public void missingFileTest() { try { new CharacterDrill2("blob", "blob", 0); fail("loaded a bad file..."); } catch (Exception e) { } public void badExampleTest() { try { new CharacterDrill2("src/c11files/characterdrill/data/", "badExample.txt", 0); fail("loaded a bad file..."); } catch (Exception e) { } }

20 © Calvin College, // header here... public class CharacterDrillPanel extends PApplet { private URI myPath; private PImage myImage; private int myTintValue; private Minim myMinim; private AudioSnippet myPronunciation; public CharacterDrillPanel() throws URISyntaxException { myPath = getPath("data/"); myMinim = new Minim(this); } public void setImage(String filename) throws URISyntaxException { myImage = loadImage(myPath + filename); myTintValue = 0; } public void setPronunciation(String filename) { myPronunciation = myMinim.loadSnippet(myPath + filename); } public void playPronunciation() { myPronunciation.play(); } // This routine computes the URI of the directory containing this class file // required by the Processing loadImage() method. private URI getPath(String relativePath) throws URISyntaxException { return CharacterDrillPanel.class.getResource(relativePath).toURI(); } public void setup() { size(300, 300); background(255); imageMode(CENTER); } public void draw() { if (myImage != null) { tint(255, myTintValue); image(myImage, width / 2, height / 2); myTintValue = constrain(myTintValue + 1, 0, 255); } public void stop() { myPronunciation.close(); myMinim.stop(); }

21 © Calvin College, PrintWriter ● The PrintWriter class can print formatted text to a text-output stream. ● Pattern: new PrintWriter(outputFile) ● The API includes these methods: – print() println()... – printf() – close() flush()

22 © Calvin College, Iteration 3 ● Analysis ● Design ● Implementation ● Test

23 © Calvin College, 2009 Example: Record Output 23 Given: the output filename and path Algorithm: Open a print writer stream to the given file. Loop forever: Prompt for and read a line of data. If the line is the sentinel Quit. else Output the line. Close the file stream/scanner.

24 © Calvin College, 2009 Example: Record Output (cont.) 24 PrintWriter fileOut = new PrintWriter(new File(path, filename)); String line = ""; while (true) { System.out.print("enter record (just enter to quit): "); line = keyboard.nextLine(); if (line.equals("")) { break; } else { fileOut.println(line); } fileOut.close(); System.out.println("data stored to: " + path + filename);

25 © Calvin College, // header information here... public class CharacterFileBuilderController extends JFrame implements ActionListener { private JLabel messageLabel; private JTextField englishField, pinyinField, imageFilenameField, soundFilenameField, sentenceField; private JButton addButton, closeButton; private PrintWriter outFile; public CharacterFileBuilderController() throws URISyntaxException, FileNotFoundException { super("Chinese Character Creator"); setDefaultCloseOperation(EXIT_ON_CLOSE); Font font = new Font("Ariel", 0, 18); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Choose an output filename"); fileChooser.showOpenDialog(this); outFile = new PrintWriter(fileChooser.getSelectedFile()); // GUI specification here... public void actionPerformed(ActionEvent event) { String actionCommand = event.getActionCommand(); if (actionCommand.equalsIgnoreCase("Add")) { outFile.print(englishField.getText() + " " + pinyinField.getText() + " " + imageFilenameField.getText() + " " + soundFilenameField.getText() + " " + sentenceField.getText()); messageLabel.setText("Record added..."); } else if (actionCommand.equalsIgnoreCase("Close")) { outFile.close(); messageLabel.setText("File saved..."); } // main() method here... }}

26 © Calvin College, Buffering ● I/O is slow relative to processing speed, so it is generally buffered. Program Input Stream Output Stream Program buffer

27 © Calvin College, Java Buffering ● Buffering can be added to file streams to improve the efficiency of I/O operations. ● A buffer is a memory area that stores up input/output data so that it can be input/output all at once. ● Patterns: new BufferedReader(new FileReader(fileNamePath)); new BufferedWriter(new FileWriter(fileNamePath));

28 © Calvin College, Uses for File I/O ● Using simple text files is unusual, but they are used, e.g.: – Log files; – Configuration files. ● Applications are more likely to use: – Database management systems; – XML files; – Lexing and parsing tools.

29 © Calvin College, Data Management ● Storing, retrieving and manipulating data sets are very common problems. ● Database Management Systems are designed to address these problems. Database Files Records Fields Characters/Strings/Integers Bits

30 © Calvin College, The Relational Data Model ● Most current DBMSs use the relational data model. ● Relational models separate the structure of the data from the data itself. Schema: Data: FieldField Type name String rank String serialNumber String NameRankSerial Number JoeColonel MaryLieutenant BobPrivate

31 © Calvin College, Structured Query Language ● SQL is the standard query language for relational databases. ● Example: SQL> SELECT name, rank FROM SoldierTable WHERE ID > ; NAME RANK Mary Lieutenant Bob Private

32 © Calvin College, Edgar F. Codd ( ) Relational Data Model image from wikipedia, June, 2006 ● Codd developed the relational model in the early 1970s. ● Included features for: – Data definition – Data queries ● Most current database systems use the relational model.

33 © Calvin College, Privacy ● Database systems allow us to build and maintain large data sets: – This can be useful for many applications. – It can also be dangerous. ● Guidelines: – Collect only what you need to collect. – Have a clear policy on what information is collected and on how it is used. – Keep the data accurate and secure. What’s the Big Idea


Download ppt "© Calvin College, 2009 1 All our knowledge brings us nearer to our ignorance, All our ignorance brings us nearer to death, But nearness to death, no nearer."

Similar presentations


Ads by Google