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

Similar documents
CS 251 Intermediate Programming Java I/O Streams

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

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

Darshan Institute of Engineering & Technology for Diploma Studies

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

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

Software 1. Java I/O

Files and Streams

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

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

1.00 Lecture 30. Sending information to a Java program

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

Lab 5: Java IO 12:00 PM, Feb 21, 2018

PIC 20A Streams and I/O

Java Input/Output. 11 April 2013 OSU CSE 1

Lecture 11.1 I/O Streams

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

Exceptions and Working with Files

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

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

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

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

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

Object-Oriented Programming Design. Topic : Streams and Files

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

Chapter 12. File Input and Output. CS180-Recitation

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

CSC 1214: Object-Oriented Programming

IT101. File Input and Output

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Question 1. (2 points) What is the difference between a stream and a file?

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Software Practice 1 - File I/O

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

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

CSPP : Introduction to Object-Oriented Programming

HST 952. Computing for Biomedical Scientists Lecture 8

Example: Copying the contents of a file

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

CN208 Introduction to Computer Programming

Streams and File I/O

Programming Languages and Techniques (CIS120)

Object-Oriented Programming in the Java language

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

CS 200 File Input and Output Jim Williams, PhD

CS112 Lecture: Streams

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

Java Programming Lecture 9

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

I/O STREAM (REQUIRED IN THE FINAL)

Object Oriented Design with UML and Java. PART VIII: Java IO

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

Data Structures. 03 Streams & File I/O

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

Exceptions and Libraries

Input-Output and Exception Handling

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

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

pre-emptive non pre-emptive

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

Java file manipulations

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

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

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

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

Chapter 10. IO Streams

Techniques of Java Programming: Streams in Java

Simple Java Input/Output

CS Week 11. Jim Williams, PhD

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Objec-ves JAR FILES. Jar files. Excep-ons. Files Streams. Ø Wrap up Ø Why Excep-ons? 9/30/16. Oct 3, 2016 Sprenkle - CSCI209 1

CPS122 Lecture: Input-Output

Active Learning: Streams

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

Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives

Lecture 4: Exceptions. I/O

Object Oriented Software Design

Object Oriented Software Design

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.

CPS122 Lecture: Input-Output

I/O Streams. Object-oriented programming

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

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

Dining philosophers (cont)

Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key)

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

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

Project #1 Computer Science 2334 Fall 2008

Web Server Project. Tom Kelliher, CS points, due May 4, 2011

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

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

Java Refresh Exercises

1.00 Lecture 31. Streams 2. Reading for next time: Big Java , The 3 Flavors of Streams

copy.dept_change( CSE ); // Original Objects also changed

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

Transcription:

Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading and Writing Advanced OOP Exceptions Collection classes Want to communicate with the user, files, etc... java.io package contains useful classes Reader, Writer talk to text streams 3 4

Using Writers Basic usage: call write method directly Need to include the newline ( \n ) if needed Can create PrintWriter object for print, println methods Writing hello Writer w = new FileWriter("hello"); w.write("hello, world!\n"); // Faster over multiple writes: BufferedWriter bw = new BufferedWriter(w); bw.write("hello,world!\n"); // More probably: PrintWriter pw = new PrintWriter(bw); // Newline will be added automatically pw.println("hello, world!"); // Cause data to be written *now* bw.flush(); 5 6 Using Reader Basic usage: call read method directly This is hard how do you know how much to read? BufferedReader includes a readline method Reading Hello Reader r = new FileReader("hello"); BufferedReader br = new BufferedReader(r); while (true) { String s = br.readline(); if (s == null) break; // End Of File System.out.println(s); 7 8

Binary files Things behind Streams Not all files are text File-backed Streams FileReader, etc. InputStream, OutputStream classes read/write raw bytes; System.in is an InputStream String-backed streams StringReader, StringWrit Similar interface System.out is an OutputStream DataInputStream and DataOutputStream read/write higher-level objects 9 10 Writing objects File I/O, an example ObjectInputStream, ObjectOutputStream parse files of simple input lan- Concept: guage readobject and writeobject methods Automatically read and write anything that implements Serializable interface print [message] include [filename] 11 12

Object design Two simple concepts: whole files and individuals lines package day5; import java.io.*; PrintParser PrintParser reads and parses a file CommandLine contains a single line 13 * Parse files of a simple command-line format. * In particular, recognize lines that look like: * * <pre> * print Some message goes here * include other-file * </pre> * * Print "print" lines to <code>system.out</code>, * and recursively process "include" lines. public class PrintParser { * Command-line entry point. 14 * * @param args The command-line arguments. public static void main(string[] args) { PrintParser pp = new PrintParser(args[0]); pp.parse(); Filename to parse. private String filename; * Create a new PrintParser to parse a particula * file. * * @param fn Name of the file to parse. public PrintParser(String fn) { filename = fn; * Parse a file, executing commands we find ther public void parse() { // Might consider trapping exceptions here. BufferedReader reader; try { reader = new BufferedReader(new FileReader(f catch (FileNotFoundException e) { System.err.println("PrintParser: could not r filename); return; // Read lines until we hit EOF. while (true) { String line; try { line = reader.readline(); catch (IOException e) { System.err.println("PrintParser: error whi

return; filename + ": " + e); Inner classes Legal to declare classes inside of other classes // Stop if EOF. if (line == null) break; // Parse the line. CommandLine cl = new CommandLine(line); String command = cl.getcommand(); if (command.equals("print")) System.out.println(cl.getArgs()); else if (command.equals("include")) { PrintParser pp = new PrintParser(cl.getArg pp.parse(); // Ignore incorrect lines. Inner class is a member of the outer one Each object of the inner class references an object of the outer class implicitly Same modifiers as fields / methods (static, public, etc) package.outer.inner 15 Anonymous classes Anonymous classes, an example Sometimes you only need a class once Need to implement an interface, etc Often don t need much in the way of implementation Common in Swing (see tomorrow) File[] files; File pdw = new File("."); files = pwd.listfiles( new FilenameFilter() { public boolean accept(file dir, String name) { return name.endswith(".java"); ); 16 17

Closures, an example Access, inner classes public File[] fileswithextension (File dir, final String ext) { return dir.listfiles( new FilenameFilter() { public boolean accept(file dir, String name) { return name.endswith("." + ext); ); Can access any field in containing object Any final function parameter or local variable in containing function 18 19 Debugging jdb It doesn t work! Java Debugger Simple solution: insert println calls in strategic places to see where your assumptions and Java s differ Harder solution: use a debugger (jdb) jdb class args Should be in root source directory (e.g. ~/java) 20 21

jdb basics Looking at data in jdb run: runs the program from beginning print (expr): prints an arbitrary expression cont: continues from current point step: do one statement, stepping into functions dump (expr): same, but prints object members where: prints call stack next: do one statement, skipping functions 22 23 Breakpoints Packaging Stop execution at some point Useful with cont and run stop at Class:line Want to distribute whole application as a file Distribute reusable set of classes Don t want to have lots of files stop in pkg.class.function() stop in Class.init clear: remove breakpoints 24 25

Java archives Building jar files jar files Build directory of class files Just a zip file jar cf file.jar *.class Can add jar files to CLASSPATH Can list individual class files Can run with java -jar file.jar Can actually put any file in a jar (resources like images) Directory names include all files therein 26 27 jars as libraries jars as applications Package up class files useful for other projects Distribute entire program as one file Put name of jar file in CLASSPATH Need to create Manifest file XML processors, 6.170 testing code, etc Can run with java -jar file.jar 28 29

Manifest destiny Looking at jars Text file with control information jar tf file.jar: lists contents Should contain: Main-Class: my.pkg.class jar xf file.jar: unpacks in current directory Include Manifest in jar file 30 31 What s in that class file? Documentation javap decompiles an existing class file javap classname prints basic class declaration Several options Want to be able to put up Web pages about your classes Document class usage, function parameters, requirements for use... javadoc: comments to HTML 32 33

Javadoc, an example * Javadoc comments always start with * a slash and two stars, and immediately * precede the code they document. class Foo { //... Functions in javadoc * Returns n factorial * * @param n Number to find the factorial of * @return n * (n - 1) *... * 2 * 1 public static int fact(int n) { //... 34 35 Fields The color of this. private Color mycolor; Javadoc bodies * Comments can use <tt>html</tt> tags * and refer to <code>class</code> * @param name description * @return description * @see pkg.class#method * @throws Exception description 36 37

Building the docs In summary javadoc pkg File I/O javadoc File.java Inner classes By default, only documents public and protected members Debugging, packaging, documenting tools 38 39 Tomorrow Swing basics More useful classes 40