Programmierpraktikum

Similar documents
FILE I/O IN JAVA. Prof. Chris Jermaine

IT101. File Input and Output

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS 251 Intermediate Programming Java I/O Streams

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Streams and File I/O

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Java Input/Output. 11 April 2013 OSU CSE 1

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Chapter 10. IO Streams

CN208 Introduction to Computer Programming

Lecture 7. File Processing

Input from Files. Buffered Reader

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Performing input and output operations using a Byte Stream

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

1.00 Lecture 30. Sending information to a Java program

STREAMS. (fluxos) Objetivos

Darshan Institute of Engineering & Technology for Diploma Studies

Object-Oriented Programming Design. Topic : Streams and Files

Software 1. Java I/O

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

HST 952. Computing for Biomedical Scientists Lecture 8

PIC 20A Streams and I/O

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Algorithms. Produced by. Eamonn de Leastar

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

CS Programming I: File Input / Output

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Exceptions and Working with Files

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

CS Programming I: File Input / Output

CS 2113 Software Engineering

Data Structures. 03 Streams & File I/O

I/O Streams. Object-oriented programming

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

I/O STREAM (REQUIRED IN THE FINAL)

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Object Oriented Software Design

Object Oriented Software Design

Events and Exceptions

File Operations in Java. File handling in java enables to read data from and write data to files

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Objec&ves. Review. Standard Error Streams

CS193j, Stanford Handout #26. Files and Streams

CSPP : Introduction to Object-Oriented Programming

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

Input-Output and Exception Handling

pre-emptive non pre-emptive

Chapter 8: Files and Security

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Software 1. תרגול 9 Java I/O

Dining philosophers (cont)

Example: Copying the contents of a file

Software 1 with Java. The java.io package. Streams. Streams. Streams. InputStreams

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Java file manipulations

Object-Oriented Programming in the Java language

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

School of Informatics, University of Edinburgh

WOSO Source Code (Java)

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

Programmierpraktikum

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

Simple Java Input/Output

CSC 1214: Object-Oriented Programming

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

Text User Interfaces. Keyboard IO plus

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary

ITI Introduction to Computer Science II

Many Stream Classes. File I/O - Chapter 10. Writing Text Files. Text Files vs Binary Files. Reading Text Files. EOF with hasmoreelements()

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

When we reach the line "z = x / y" the program crashes with the message:

Full file at

C17: File I/O and Exception Handling

Chapter 10 Input Output Streams

Simple Java Reference

CPIT 305 Advanced Programming

Byte and Character Streams. Reading and Writing Console input and output

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

What is Serialization?

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

String temp [] = {"a", "b", "c"}; where temp[] is String array.

Transcription:

Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 05/07/2012 10:31 AM

Input / Output Streams 2 of 21 05/07/2012 10:31 AM

Java I/O streams stream from/to everywhere screen file internet connection... transmit all kind of data byte, char, int,... string, objects,... 3 of 21 05/07/2012 10:31 AM

java.io IO - communiation with the world input / output a class for every type of stream modern programming know what exists look it up exception handeling mandatory for IO input files may not be present possibly no writing permissions on output... 4 of 21 05/07/2012 10:31 AM

byte streams IO byte per byte input/output byte by byte is low level, inefficient read() returns integer (Unicode, table) : -1 at end null: object not yet been instantiated import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; // normally just use import java.io.*; public class CopyBytes public static void main(string[] args) throws IOException // what happens if you would just use // public static void main(string[] args) FileInputStream in = null; FileOutputStream out = null; try in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; // *** start loop over all bytes in input file while ((c = in.read())!= -1) out.write(c); // *** all reading has been done 5 of 21 05/07/2012 10:31 AM

finally // finally: always close streams if (in!= null) in.close(); if (out!= null) out.close(); appending to output file with true catch exception import java.io.*; public class CopyBytes public static void main(string[] args) // no exception thrown try FileInputStream instream = new FileInputStream("input.txt"); FileOutputStream outstream = new FileOutputStream("output.txt",true); // are equivalent new FileOutputStream("output.txt",false); // new FileOutputStream("output.txt"); // new FileOutputStream("output.txt",(1==2)); int c; while ((c = instream.read())!= -1) outstream.write(c); catch(ioexception e) System.out.println(e.toString()); // end of CopyBytes.main() // end of CopyBytes 6 of 21 05/07/2012 10:31 AM

formatted output PrintWriter: has member function.print().printf() formatted output is alway sent to a buffer, and not directly to the output file use member function.flush() to sent bufffer to file import java.io.*; public class FormattedOutput public static void main(string[] args) try PrintWriter myoutput = new PrintWriter("output.txt"); for (int i=0;i<8;i++) myoutput.printf("%2d modulo 3 is %2d\n",i,i%3); myoutput.flush(); // sent buffer to file catch(ioexception e) System.out.println(e.toString()); // end of FormattedOutput.main() // end of FormattedOutput 7 of 21 05/07/2012 10:31 AM

buffered input buffering every read/write request to disk is slow (try to read/write a 100 GByte file without buffering) buffering: systems reads/writes large chunks of data to file at once BufferedReader: wrapper around a Reader has member function.readline() 8 of 21 05/07/2012 10:31 AM

9 of 21 05/07/2012 10:31 AM

buffered input with formatted output FileInputStream: byte Reader: 8 bits FileReader: char Reader: 16 bits reading String data line by line import java.io.filereader; // character reader import java.io.filewriter; // character writer import java.io.bufferedreader; // buffering input import java.io.printwriter; // formatting output import java.io.ioexception; public class CopyLines public static void main(string[] args) try BufferedReader inputstream = new BufferedReader(new FileReader("input.txt")); PrintWriter outputstream = new PrintWriter(new FileWriter("output.txt")); // or new PrintWriter("output.txt"); String s; while ((s = inputstream.readline())!= null) outputstream.println(s); outputstream.flush(); catch(ioexception e) System.out.println(e.toString()); // end of CopyLines.main() // end of CopyLines 10 of 21 05/07/2012 10:31 AM

buffered and formatted ouput a must: buffering input/output for large data sizes import java.io.*; public class FormattedOutput public static void main(string[] args) try PrintWriter myoutput = new PrintWriter( // for formatting new BufferedWriter( // for buffering new FileWriter("output.txt"))); // ouput stream for (int i=0;i<8;i++) myoutput.printf("%2d modulo 5 is %2d\n",i,i%5); myoutput.flush(); // sent buffer to file catch(ioexception e) System.out.println(e.toString()); // end of FormattedOutput.main() // end of FormattedOutput 11 of 21 05/07/2012 10:31 AM

scientific data files how to read lists of numbers? typical science data file # list of planet properties by E.T. Skywatcher # actually from http://www.astronomynotes.com/solarsys/plantbla.htm # # Planet Mass (* ME) # Diameter (km) # density g/cm3 # oblateness [=(De-Dp)/De] # rotation [h or d] # distance (A.U.) # revolution [d or y] # eccentricity # inclination [deg] # axis tilt [deg] # # String double double double double double String double String double double double # ndata ### 9 Mercury 0.0553 4880 5.43 0.000 58.81 d 0.387 87.97 d 0.2056 7.0 0.1 Venus 0.815 12104 5.20 0.000 243.69 d 0.723 224.70 d 0.0068 3.4 177.3 Earth 1.000 12742 5.52 0.0034 23.9345 h 1.000 365.26 d 0.0167 0.00 23.45 Mars 0.107 6780 3.93 0.0065 24.623 h 1.524 686.98 d 0.0934 1.85 25.19 Jupiter 317.83 139822 1.33 0.0649 9.925 h 5.203 11.86 y 0.04845 1.305 3.12 Saturn 95.162 116464 0.687 0.098 10.50 h 9.539 29.46 y 0.05565 2.489 26.73 Uranus 14.536 50724 1.32 0.023 17.24 h 19.182 84.01 y 0.0472 0.773 97.86 Neptune 17.147 49248 1.64 0.017 16.11 h 30.06 164.79 y 0.00858 1.773 29.56 Pluto 0.0021 2274 2.05 0.0 6.405 d 39.53 247.68 y 0.2482 17.15 122.46 always include data description in comment section 12 of 21 05/07/2012 10:31 AM

lines starting with a hashtag # are ignored by most plotting utilities 13 of 21 05/07/2012 10:31 AM

scanning data input files scanning for data: double, int,... Scanner wraps a Reader new Scanner(System.in) for console data input has member functions Boolean.hasNext() : has next entry, seperated by blanks String.next() : next entry as a String object int.nextint() : next entry as a int primitive double.nextdouble() : next entry as a double primitive... note: use (string1.equals(string2)) for comparing two strings, (string1==string2) is not secure import java.io.*; import java.util.scanner; public class DataInput public static void main(string[] args) try Scanner myscanner = new Scanner( new FileInputStream("planetsData.list")); 14 of 21 05/07/2012 10:31 AM

boolean readingcomments = true; while (readingcomments) // skipping initial comments if (myscanner.next().equals("###")) readingcomments = false; int ndata = myscanner.nextint(); System.out.printf("# ndata %7d \n",ndata); String name; double mass; int diameter; while (myscanner.hasnext()) name = myscanner.next(); mass = myscanner.nextdouble(); diameter = myscanner.nextint(); System.out.printf("# %10s %7.2f %8d \n",name, mass, diameter); for (int i=0;i<10;i++) myscanner.next(); // skipping rest of line catch(ioexception e) System.out.println(e.toString()); // end of DataInput.main() // end of DataInput 15 of 21 05/07/2012 10:31 AM

output of objects object output streams all classes descendents of the Object class instantiated Serializable objects can be sent to output in one piece all classes can be made Serializable public class myclass implements Serializable Array objects are serializable per definition on input one needs to check the type of Object read using instanceof data files containing serializabled objects are binary and not human readable import java.io.*; public class ObjectsIo public static void main(string[] args) // *** // *** generate objects and write objects to file // *** String[] stringarrayobject = "This","is","an","array","of","strings"; int[] intarrayobject = 4444,333,22,1; try ObjectOutputStream myoutput = new ObjectOutputStream( new FileOutputStream("containsObject.txt")); 16 of 21 05/07/2012 10:31 AM

myoutput.writeobject(stringarrayobject); myoutput.writeobject(intarrayobject); catch(ioexception e) System.out.println(e.toString()); // *** // *** read objects from file // *** try ObjectInputStream myinput = new ObjectInputStream( new FileInputStream("containsObject.txt")); Object obj = null; while ((obj = myinput.readobject())!= null) if (obj instanceof String[]) // string array String[] ss = (String[])obj; // casting Object to String[] for (int j=0;j<ss.length;j++) System.out.printf("%s ",ss[j]); System.out.printf("\n"); if (obj instanceof int[]) // int array int[] ii = (int[])obj; // casting Object to int[] for (int j=0;j<ii.length;j++) System.out.printf("%d ",ii[j]); System.out.printf("\n"); catch (EOFException ex) // EOF exception System.out.println("End of file reached."); catch(ioexception e) System.out.println(e.toString()); catch (ClassNotFoundException e) System.out.println(e.toString()); 17 of 21 05/07/2012 10:31 AM

// end of ObjectsIo.main() // end of ObjectsIo 18 of 21 05/07/2012 10:31 AM

exercise: IO and OOP Write a program for object oriented input/output. define a serializable class Planet storing all planet properties read the planet data file and create an instantiation of Planet for every planet write all instantiated Planet objects to file read the Planet objects from file, print data to console as a formatted table 19 of 21 05/07/2012 10:31 AM

directory listings System.getProperty() for various properties of operating system.isdirectory() /.isfile() for File objects import java.util.*; import java.io.*; import java.math.*; class DirectoryHandling public static void main(string args[]) // *** // *** open file handler / directory listing // *** String inputdirpath = null; if (args.length==1) inputdirpath = args[0]; // directory path else if (args.length==0) inputdirpath = System.getProperty("user.dir"); // working directory else System.out.printf("number of arguments must be 0/1 and not %d\n", args.length); return; // exit main() File inputdir = new File(inputDirPath); // open file or directory String[] inputdirfiles = null; if (inputdir.isdirectory()) // got a directory? inputdirfiles = inputdir.list(); else System.out.println("input not a directory: " + inputdirpath); 20 of 21 05/07/2012 10:31 AM

return; // exit main() // *** // *** (limited) output of directories/files found // *** String fileseparator = System.getProperty("file.separator"); // is "/" on UNIX and "\" on Windows // System.out.println(" "); System.out.println("files and directories found in: " + inputdirpath); System.out.println(" "); for (int i=0;i<math.min(10,inputdirfiles.length);i++) String fullpath = inputdirpath + fileseparator + inputdirfiles[i]; File listfile = new File(fullPath) ; // open file or directory if (listfile.isfile()) // got a file? System.out.println("file: " + fullpath); else System.out.println(" dir: " + fullpath); // end of DirectoryHandling.main() // end of DirectoryHandling 21 of 21 05/07/2012 10:31 AM