1 / 22

Sitzung 11: IO – Streams in Java

Sitzung 11: IO – Streams in Java. Überblick. Lesen und Speichern in Dateien: Filestreams und Tokenizer Kurzeinführung in Exceptions und das Exception-Handling in Java. Streams. Daten werden sequentiell aus einem Daten- Strom gelesen, bzw. in einen Daten- Strom geschrieben

toan
Télécharger la présentation

Sitzung 11: IO – Streams in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Sitzung 11: IO – Streams in Java Sitzung 11

  2. Überblick • Lesen und Speichern in Dateien:Filestreams und Tokenizer • Kurzeinführung in Exceptionsund das Exception-Handling in Java I/O – Streams in Java

  3. Streams • Daten werden sequentiell aus einem Daten-Strom gelesen, bzw. in einen Daten-Strom geschrieben • Ein solcher Datenstrom kann zu unterschiedlichen Quellen (Datei, Speicher, Netzressource, Konsole, Objekte, …) und Datenformate (Binär, Text, …) verbunden sein – zeigt aber immer dasselbe Verhalten I/O – Streams in Java

  4. Reading open a stream while more information read information close the stream Writing open a stream while more information write information close the stream Lesen und Schreiben in Streams • Das Prinzip ist immer gleich: I/O – Streams in Java

  5. 2 Arten von Streams in Java Character-StreamsByte-Streams Mehr Infos im Sun-Tutorial unter:Essential Java Classes  Lesson: I/O: Reading and Writing (but no 'rithmetic) I/O – Streams in Java

  6. Copy Beispiel aus dem Tutorial import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); // file treated as char stream FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } I/O – Streams in Java

  7. Beispiel Beispiel Punkte schreiben/lesen • Einfaches ARC-Generate Ascii-Dateiformat für Punkte Mehr Infos unter:http://gis.washington.edu/cfr250/lessons/data_export/ I/O – Streams in Java

  8. Beispiel Punkte schreiben - 1 import java.util.*; import java.io.*; class GeneratePointFileWriter { void write(String fileName, java.util.List pointList) throws IOException { PrintWriter pw = new PrintWriter(new FileWriter(new File(fileName))); double x, y; Point p; int i = 1; Iterator pointIterator = pointList.iterator(); while (pointIterator.hasNext()) { p = (Point)pointIterator.next(); x = p.getX(); y = p.getY(); pw.println(i + ", " + x + ", " + y); i++; } pw.println("END"); pw.close(); } } I/O – Streams in Java

  9. Beispiel Punkte schreiben - 2 … final JFileChooser fileChooser = new JFileChooser(); int returnVal = fileChooser.showSaveDialog(GISFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); GeneratePointFileWriter pointWriter = new GeneratePointFileWriter(); try { pointWriter.write(file.getAbsolutePath(), model.getPointLayer() ); } catch (Exception IOException) { // writing failed: JOptionPane.showMessageDialog(GISFrame.this, "Can not store File:" + file.getAbsolutePath(), "Writing Error", JOptionPane.ERROR_MESSAGE); } }… I/O – Streams in Java

  10. Beispiel Punkte lesen - 1 public class GeneratePointFileReader { public List read(String name) throws IOException { BufferedReader in = new BufferedReader(new FileReader(name)); List pointList = new ArrayList(); double x, y; int i = 0; // read first line String line = in.readLine(); while (!line.equals("END")) { // using StringTokenizer to parse string; using comma as delimeter StringTokenizer st = new StringTokenizer(line, ", ", false); st.nextToken(); //overread point-number // extract the point x = Double.valueOf(st.nextToken()).doubleValue(); y = Double.valueOf(st.nextToken()).doubleValue(); Point p = new Point(x, y); pointList.add(p); // read next line line = in.readLine(); } in.close(); return pointList; } } I/O – Streams in Java

  11. Beispiel Punkte lesen - 2 … final JFileChooser fileChooser = new JFileChooser(); int returnVal = fileChooser.showOpenDialog(GISFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); GeneratePointFileReader pointReader = new GeneratePointFileReader(); try { newPoints = pointReader.read(file.getAbsolutePath()); } catch (Exception IOException) { // reading failed: JOptionPane.showMessageDialog(GISFrame.this, "Can not read File:" + file.getAbsolutePath(), "Reading Error", JOptionPane.ERROR_MESSAGE); } } … I/O – Streams in Java

  12. StringTokenizer • Dient der Zerlegung einer Zeichenkette (in einem String oder Stream) in Teilzeichenketten • Voreingestellte Trennzeichen sind Leerzeichen, Tabulatoren und Zeilenvorschübe • Es können andere Trennzeichen definiert werden Mehr Infos: www.javabuch.de; Kapitel 17.1 I/O – Streams in Java

  13. Beispiel StringTokenizer while (!line.equals("END")) { // using StringTokenizer to parse // string; using comma as delimeter StringTokenizer st = new StringTokenizer(line, ", ", false); st.nextToken(); //overread point-number // extract the point x = Double.valueOf(st.nextToken()).doubleValue(); y = Double.valueOf(st.nextToken()).doubleValue(); Point p = new Point(x, y); pointList.add(p); // read next line line = in.readLine(); } I/O – Streams in Java

  14. Überblick Exceptions in Java • Eine Exception ist ein außergewöhnliches Verhalten, dass den normalen (= geplanten) Programmfluss unterbricht (Lese- oder Schreibefehler, Division durch Null, …) • Eine Exception wird dort geworfen (throw),wo der Fehler auftrittund dort aufgefangen (try…catch), wo der Fehler behandelt werden soll • Exceptions müssen (irgendwann) aufgefangen werden ! Mehr Infos im Sun-Tutorial unter:Essential Java Classes  Lesson: Handling Errors with Exceptions I/O – Streams in Java

  15. Exceptions in Java – try & catch • Der try catch Block: try { // code, der Fehler auslösen könnte } catch ( . . . ) { . . .} catch ( . . . ) { . . .} . . . I/O – Streams in Java

  16. Exceptions in Java – try & catch • Unterschiedliche Spezialisierung von der Basisklasse Exception für unterschiedliche Behandlungen: try { … //unsichere Array-Index Zugriffe … //unsichere IO-Methoden } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " +e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } I/O – Streams in Java

  17. Exceptions in Java – try & catch • In dem Beispiel zum Einlesen von Punkten: try { pointWriter.write(file.getAbsolutePath(), model.getPointLayer() ); } catch (IOException ioe) { // writing failed: JOptionPane.showMessageDialog(GISFrame.this, "Can not store File:" + file.getAbsolutePath(), "Writing Error", JOptionPane.ERROR_MESSAGE); } I/O – Streams in Java

  18. Exceptions in Java – throw • Eine Methode wirft eine Exception weiter: • Eine Methode erzeugt und wirft eine Exception: void write(String fileName, List pointList) throws IOException { BufferedReader in = new BufferedReader(new FileReader(name)); int b = in.read(); ... } public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(); // EmptyStackException is a self created class // that is derived from Exception ... } I/O – Streams in Java

  19. Aufgabe 7 • Erweiterung des Programms: • Polylinien-Layer unter Verwendung des bereitgestellten GeneratePolylineFileReader einlesen und darstellen (sofort) • GPFR & Beispieldaten: Exchange-Platte unter \Geosoftware_I\Geowissenschaftler Kurs SS04\Aufgabe7 • Punkt-Layer im ARC ASCII Generate Format einlesen und abspeichern (Hausaufgabe) • Die angegebenen Stellen in dem Tutorial lesen und erarbeiten ! • Abgabe: Samstag 24.07. 24:00 ! I/O – Streams in Java

  20. Aufgabe – Format für Liniendateien • Das ARC ASCII Generate Format zur Abspeicherung von Polylinien • Jede Linie beginnt mit einer ID und endet mit END • Die Datei endet mit END I/O – Streams in Java

  21. Aufgabe – Format für Polygondateien • Das ARC ASCII Generate Format zur Abspeicherung von Polygonen • Jedes Polygon beginnt mit einer ID sowie einem Labelpoint und endet mit END • Die Datei endet mit END I/O – Streams in Java

  22. Vorschlag für ein Klassendiagramm I/O – Streams in Java

More Related