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