CS 200 - Week 11 Jim Williams, PhD.

Slides:



Advertisements
Similar presentations
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Advertisements

Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Unit 8 (Basic Input/Output) Content A) Using files in JavaUsing files in Java B) Exception HandlingException Handling C) Filter StreamFilter Stream D)
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Reading Parameters CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D.
Java IO Exploring the java.io package and living to talk about it.
CHAPTER 3 File Output.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Reading from a file and Writing to a file
Lecture 5 Text File I/O; Parsing.
Building Java Programs
Strings and File I/O.
File Input and Output TOPICS File Input Exception Handling File Output.
Lecture Note Set 1 Thursday 12-May-05
I/O Basics.
Accessing Files in Java
CS Week 10 Jim Williams, PhD.
Going from C++ to Java Jayden Navarro.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
CS Week 14 Jim Williams, PhD.
Some File I/O CS140: Introduction to Computing 1 Savitch Chapter 9.1, 10.1, /25/13.
CS 200 Arrays, Loops and Methods
File Input and Output TOPICS File Input Exception Handling File Output.
Programming in Java Files and I/O Streams
CS 302 Week 15 Jim Williams, PhD.
CSS161: Fundamentals of Computing
Објектно орјентисано програмирање
CS 200 File Input and Output
CS Week 8 Jim Williams, PhD.
CS 200 Using Objects Jim Williams, PhD.
CS 200 Command-Line Arguments & Exceptions
File class File myFile=new File(“c:/javaDemo/aa
CS Week 7 Jim Williams, PhD.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
Week 6 CS 302 Jim Williams, PhD.
File I/O ICS 111: Introduction to Computer Science I
CS 200 Command-Line Arguments & Exceptions
CS 200 Loops Jim Williams, PhD.
CS 302 Week 13 Jim Williams, PhD.
CS 200 Arrays Jim Williams, PhD.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Chapter 9 Strings and Text I/O
Web Design & Development Lecture 8
CS Week 2 Jim Williams, PhD.
CS 200 Command-Line Arguments & Exceptions
Week 7 CS 302 Jim Williams.
CS302 Week 6 Jim Williams.
CS 200 Additional Topics and Review
Java Chapter 2 (Estifanos Tilahun Mihret--Tech with Estif)
David Davenport Spring 2005
Lecture 6 Text File I/O Parsing Text CS2012.
Presentation transcript:

CS 200 - Week 11 Jim Williams, PhD

This Week Exam 2 - Thursday Team Lab: Exceptions, Paths, Command Line Review: Muddiest Point Lecture: File Input and Output

Objectives Describe a text file including meta information and contents. Trace, explain and write programs that read the contents of a text file. Trace, explain and write code that writes a text file.

Relative vs Absolute Paths Relative - based on current location Absolute - based on fixed location

From within log what is a relative path to tasks? / meta log mylyn taskListIndex segments tasks contexts plugins history ../mylyn/tasks /meta/mylyn/tasks ./mylyn/tasks ../tasks

From within tasks what is a relative path to mylyn? / meta log mylyn taskListIndex segments tasks contexts plugins history /meta/mylyn ../mylyn ./../mylyn/tasks ..

From within tasks what is an absolute path to log? / meta log mylyn taskListIndex segments tasks contexts plugins history /meta/log ../../log ./meta/log /log

What is the correct output? Hello Fred 100,3.14 Hello Fred 100,3.14159 00100,3.14 public static void main(String[] args) { String name = "Fred"; int num = 100; double dNum = 3.14159; System.out.printf("Hello %6s\n", name); System.out.printf("%05d,%.2f", num, dNum); } http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

File Input and Output Key Classes: File - meta information Scanner, InputStream, FileInputStream, FileReader, BufferedReader OutputStream, FileOutputStream, PrintStream, PrintWriter

File Use to access file meta information File file = new File("src/CheckFile.java"); exists(), isDirectory(), isDirectory(), getName(), getPath(), canRead(), canWrite(), etc. import java.io.File; public class CheckFile { public static void main(String[] args) { File file = new File("src/CheckFile.java"); System.out.println( "exists(): " + file.exists()); System.out.println( "isDirectory(): " + file.isDirectory()); System.out.println( "isFile(): " + file.isFile()); System.out.println( "getAbsolutePath(): " + file.getAbsolutePath()); System.out.println( "getName(): " + file.getName()); System.out.println( "getPath(): " + file.getPath()); System.out.println( "canRead(): " + file.canRead()); System.out.println( "canWrite(): " + file.canWrite()); System.out.println( "getFreeSpace(): " + file.getFreeSpace()); System.out.println( "getTotalSpace(): " + file.getTotalSpace()); System.out.println( "getUsableSpace(): " + file.getUsableSpace()); }

What does this do? public static void show(File file, String depth) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { System.out.printf("%s%s\n", depth, files[i].getName()); if (files[i].isDirectory()) show(files[i], depth + " "); } public static void main(String[] args) { File file = new File("."); show(file, " "); import java.io.File; public class Show { public static void show(File file, String depth) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { System.out.printf("%s%s\n", depth, files[i].getName()); if (files[i].isDirectory()) show(files[i], depth + " "); } public static void main(String[] args) { File file = new File("."); show(file, " ");

File Input

What is print out? 8 line 3 hello 2 8 line 5 line 5 line 3 line 4 line File f = new File( "myfile.txt"); Scanner scnr = new Scanner( f); scnr.nextLine(); int count = 4; if ( scnr.hasNextInt()) count = scnr.nextInt(); else { } for ( int i = 0; i < count; i++) System.out.println( scnr.nextLine()); 8 line 5 line 3 line other 3 hello 2 8 line 5 line 3 line 4 line

What does this do? File file = new File(FILENAME); Scanner inFile = null; try { inFile = new Scanner(file); while (inFile.hasNext()) { //process each line of the file } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (inFile != null) inFile.close();

Try with Resources //Prior to Java 7 BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } //In Java 7 try ( BufferedReader br = new BufferedReader(new FileReader(path)) ) { return br.readLine(); }

What does this do? StringBuilder sb = new StringBuilder(); try ( //try with resources, calls close when done Scanner input = new Scanner( sourceFile); ) { while ( input.hasNext() ) { String s1 = input.nextLine(); String s2 = s1.replaceAll( args[1], args[2]); sb.append(s2 + "\n"); } https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

If methodA throws GreenException then output is? public static void main(String[] args) throws GreenException { boolean logging = false; try { methodA(); System.out.print("1"); } catch( BlueException e) { System.out.print("2"); } catch( GreenException e) { if ( logging) System.out.print("3"); throw e; } System.out.print("4"); 234 4 34 stack trace try it

Can you catch unchecked exceptions? yes, all throwables no, only checked exceptions

Who/What is 'checking' the checked exceptions? programmer user compiler virtual machine (JVM

What will print out? A public static void change( char [][] map) { map[1][1] = 'A'; } public static void main( String []args ) { char [][] map = new char[5][4]; map[1][1] = 'B'; change( map ); System.out.println( map[1][1]); A B wish I knew other

What will print out? public static void change( char [][] address ) { address [1][1] = 'A'; } public static void main( String []args ) { char [][] address = new char[5][4]; address [1][1] = 'B'; change( address ); System.out.println( address [1][1]); A B wish I knew other

Review Arrays and Methods public static void change( char [][] map) { map[1][1] = 'A'; } public static void main( String []args ) { char [][] map; map = new char[5][4]; change( map ); System.out.println( map[1][1]);

How many 'map' variables are there? public static void change( char [][] map) { map[1][1] = 'A'; } public static void main( String []args ) { char [][] map; map = new char[5][4]; change( map ); System.out.println( map[1][1]); 1 2 3 other

Is main 'map' on stack or heap? public static void change( String[][] map) { map[1][1] = "A"; } public static void main( String []args ) { String [][] map = new String[5][4]; map[1][1] = "B"; change( map ); System.out.println( map[1][1]); stack heap other

What is data type of map[1]? public static void change( char [][] map) { map[1][1] = 'A'; } public static void main( String []args ) { char [][] map; map = new char[5][4]; change( map ); System.out.println( map[1][1]); char char [] char [][] other

Read File - Application Some Data Sets https://github.com/fivethirtyeight/data/find/8eb18e0b6115ae6fcfb49bf81ccdd01cbe 37906c http://rs.io/100-interesting-data-sets-for-statistics/ http://www.gutenberg.org/ebooks/29765 https://github.com/dwyl/english-words import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class AnalyzeData { public static void main(String[] args) { File dataFile = new File( "./all-ages.csv"); //System.out.println( dataFile.exists()); File outFile = new File( "./myData.txt"); PrintWriter writer = null; Scanner input = null; try { writer = new PrintWriter( outFile); input = new Scanner( dataFile); String header = input.nextLine(); writer.println( header); while ( input.hasNextLine()) { String line = input.nextLine(); if ( line.contains("COMPUTER")) { // writer.println(line); //System.out.println( line); String [] lineParts = line.split(","); writer.print( lineParts[1]); writer.print( "\t"); writer.println( lineParts[5]); // System.out.print( lineParts[0]); // System.out.print( ">"); // System.out.print( lineParts[1]); // System.out.print( lineParts[ lineParts.length-1]); // System.out.println(); } } catch ( FileNotFoundException e) { e.printStackTrace(); } finally { if ( input != null) input.close(); if ( writer != null) writer.close();

File Output

What does this do? String name = "myfile.txt"; File aFile = new File(name); PrintWriter output = new PrintWriter( aFile); output.printf("This is the contents of %s.\n", name); output.close();

What does this do? PrintWriter writer = null; try { writer = new PrintWriter( SEEDS_FILENAME); for ( Seed s : seeds) { writer.printf("%f, %f\n", s.getX(), s.getY()); } } catch ( IOException e) { System.err.println("Unable to write to " + SEEDS_FILENAME); } finally { if ( writer != null) writer.close();