Lab 5: Java IO 12:00 PM, Feb 21, 2018
|
|
- Rosemary Lucas
- 6 years ago
- Views:
Transcription
1 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers Buffering and Flushing Reading and Writing Handling IO Exceptions Concatenate Finally Streams Interactivity Fun with Words Files Files and Directories Directory Listing Just for Fun: File Finder Objectives By the end of this lab, you will be able to: ˆ read from and write to files, buffers, and streams in Java ˆ manipulate Files in Java ˆ handle some of Java s IO exceptions Setup We provide sample text files in the /course/cs0180/src/poems directory for you to use during this lab. But you should feel free to create your own sample text files, if you find that ours bore you.
2 Also, you should copy over our source file: cp /course/cs0180/src/lab05/src/* /course/cs0180/src/lab05/src 1 The Java IO Library The Java Application Program Interface (API) is the set of interfaces of the Java libraries. In this lab, you will learn about the java.io package, a standard Java library. IO stands for input/output, and this library handles input and output for Java programs. Task: Quickly browse through the java.io package summary. You will notice that there are lots and lots of classes in this library. Don t spend too much time trying to understand everything in this package in detail right now; learning to read library documentation takes practice. But do come back to this task later, because this particular skill (which requires an investment up front) may save you more time than any other in your future CS endeavors. You will also ned the java.io library in your assignments in CS 18. In today s lab, you will be using the java.io library to read from and write to files, buffers, and streams. These are the specific classes that you will interact with today: FileReader, FileWriter, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamReader, and File. Of primary interest to us will be the methods for interfacing with these classes. 2 Program Arguments Much like functions, procedures, and methods take arguments as input, programs can also take arguments as input. The avenue by which programs accept inputs is the main method s argument, String[] args, which declares that your program takes as input an array of Strings called args. Before this lab, your programs haven t taken in any arguments, so the args array was empty. The notable exception to this was Showdown, where the user did pass in some arguments. The args array refers to any strings that might be handed to a program via Eclipse (or the command line if you run programs that way). Here is an example of a class, PrintArgs, with only a single method main, that simply prints its arguments. /** * A class to print command - line arguments. */ public class PrintArgs { public static void main(string[] args) { for (String arg : args) { System.out.println(arg); 2
3 When you run the program with the input hi there everybody the values of the the 0th, 1st, and 2nd strings in the args array are set to the strings "hi", "there", and "everybody", respectively. Hence, that is what is printed when the for loop iterates over the array as seen below. hi there everybody To run your program with command-line arguments in Eclipse, go to Run Run Configurations and select Arguments. On the left hand menu, make sure to select the program you want to run. Then, type the names of your arguments in the Program Arguments box, click Apply, and then run your program. Task: Write the PrintArgs class and practice running it in Eclipse with different arguments. 3 Readers, Writers, and Buffers Task: Take a quick look at the FileReader, FileWriter, BufferedReader, and BufferedWriter APIs. 3.1 Buffering and Flushing When you read and write data, you are reading from and writing to computer memory. This is expensive in terms of time. Buffering is a process that speeds this up. With a buffer, you read in data and wait to process it or write it out until a significant amount has been read in. Then the data is written into computer memory in one go we say the data has been flushed. For example, if you are writing to a file, the writer will not write each individual line to the file. Instead, it will wait until a lot of lines are waiting to be written and at that point, write all of those lines to the file. 3.2 Reading and Writing Reading/writing from/to a file consists of a few basic steps: 1. Construct a FileReader/FileWriter with a filename as a String (including its path) as an argument 2. Construct a BufferedReader/BufferedWriter from this FileReader/FileWriter 3. Read from/write to the file using the BufferedReader/BufferedWriter 4. Close the reader/writer These steps are explained in more detail below. To read from a file, you construct a FileReader. One way to do this is to pass in to the constructor the name of the file you wish to read: 3
4 FileReader freader = new FileReader("/course/cs0180/src/lab05/howl"); When a FileReader is constructed, the file is opened. Any time you want to read anything line-by-line (including user input, which we will get to later), you ll want to use a BufferedReader. Using a BufferedReader instead of just a FileReader ensures that your data is read in appropriately-sized blocks. Given a FileReader, you can create a BufferedReader like this: BufferedReader breader = new BufferedReader(fReader); And here is how you use a BufferedReader to read a file line-by-line: String line = breader.readline(); while (line!= null) { System.out.println(line); line = breader.readline(); breader.close(); The readline method, which does exactly that ( read lines ), allows you to read from a file line-by-line. Along the way, it returns each line it reads as a String, until it encounters an EOF, at which point there no further data to read, and it returns null. When you are done manipulating your file, you must always close it. To close a FileReader, you use the close method: freader.close(); In order to read from a file, we use a FileReader wrapped in a BufferedReader. Similarly, in order to write to a file, we use a FileWriter wrapped in a BufferedWriter: FileWriter fwriter = new FileWriter("/course/cs0180/src/lab05/file.txt") BufferedWriter bwriter = new BufferedWriter(fWriter); Whenever you want to write to a file, you should wrap a FileWriter in a BufferedWriter like above. In order to write, you should use the write method. bwriter.write("i am writing to a file!"); bwriter.flush(); bwriter.close(); After you are done writing to your buffer, you need to flush it. That is, you must tell Java to write everything that is currently stored in your buffer to the FileWriter. If you properly close your BufferedWriter, it will be flushed automatically. So you should not usually need to explicitly call the flush method, but rather you should flush your buffers implicitly by closing them when you are done reading or writing. 3.3 Handling IO Exceptions A lot of things can go wrong when working with IO. Methods can easily encounter unexpected input or problems. It is your responsibility as a programmer to handle these exceptions gracefully, and protect the user from unexpected behavior and program crashes. 4
5 In Java, the way to handle exceptions is with a try/catch block. In this scenario, the try block executes first. If an exception is thrown in the try block and that type of exception is caught in the catch block, the catch block will execute, instead of the program throwing the exception. One exception you may come across when working with IO is the IOException which is thrown from many methods that handle input and output. In order to use readers and writers while checking for this exception, you might do something like this: try { BufferedReader reader = new BufferedReader(new FileReader("/path/file" )); String line = reader.readline(); System.out.println(line); reader.close(); catch (IOException e) { System.out.println("Encountered an error: " + e.getmessage()); This code catches the IOException and handles it, in this case by informing the user that the program encountered an error. Note that if in the try block, an exception other than an IOException, such as an IllegalArgumentException, had instead been thrown, the catch block would not have caught that exception. 3.4 Concatenate The word concatenate means to chain things together, one after the other. The linux command cat, short for concatenate, concatenates files. Task: Try out the cat command on a few of your own files. Note: You can also use the cat command on a single file! Try that and see what it does. Task: In a class called Cat, write a method called cat that takes as input a buffered reader and a buffered writer, continuously reads lines from the reader, and writes those lines to the writer until EOF is reached. Task: In your Cat class, write a main method that takes as input two file names, and then invokes your cat method to read the contents of the first and write it to the second. In this and all future tasks, be sure to print out an appropriate error message if a FileNotFoundException or IOException is thrown. Note: We have provided you a test class to test your cat method; be sure to use it to ensure that your method works! Fill in the paths with files that you test with. You ve reached a checkpoint! Please call over a lab TA to review your work. 3.5 Finally You ve written code using try/catch blocks, which seem safe and able to handle any kind of forseeable issue your code may encounter. However, this code doesn t perfectly handle the IOException 5
6 because we might encounter an IOException in one of the earlier lines of the try clause (e.g., when trying to read a line from the BufferedReader), and be redirected to the catch block before getting a chance to close the reader. Fortunately, Java has our backs with something called a finally block. A finally block is always executed regardless of whether or not an exception is caught. So we can sleep soundly knowing we at least tried to close our reader. BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("/path/file")); String line = reader.readline(); System.out.println(line); catch (IOException e) { System.out.println("Encountered an error: " + e.getmessage()); finally { try { reader.close(); catch (IOException e) { System.out.println("Encountered an error closing the reader: " + e. getmessage()); This code may look a little funky to you, and that s because it is. Because closing a reader can throw its own IOException, we need another try/catch block within our finally block. 1 Another common exception you may encounter (and should handle) is the FileNotFoundException. This exception occurs when you try to open a file that doesn t exist or is inaccessible (or if you pass in the incorrect file path). For instance, suppose you are trying to read from a file called myfile that is not in the current directory, like this: FileReader freader = new FileReader("myFile"); Since myfile is not in your current directory, you have inputted an incorrect filepath. Therefore, this code will throw a FileNotFoundException, since the FileReader is attempting to read from a file that does not exist. Note: As you proceed with the tasks in this lab, you should be sure to properly handle IOException s and FileNotFoundExceptions. Also note that you can multiple catch blocks for one try block, so you can catch multiple exceptions. Task: Go back to your code from the previous task, and modify it so it uses finally. For the remaining tasks in this lab, where applicable, be sure to use try/catch/finally blocks! You ve reached a checkpoint! Please call over a lab TA to review your work. 1 If it seems like there ought to be a better way, there is now! A recent version of Java added a construct called a try-with-resources block that simplifies this process. While this construct will not be covered in CS 18, you can read more about it here. 6
7 4 Streams 4.1 Interactivity The buffered readers and writers you have been using are objects that are responsible for buffering streams of data (much like when you stream video online, and you need to wait for it to buffer). The stream of data being buffered might originate from a file, as we saw already. However, user input to and from the console also travels on data streams! In this part of the lab, you will learn how to read user input from the console in order to make your programs interactive. Although you may not know it, you ve used input and output streams before. System.out is the standard output stream. Whenever you use System.out.println, you re sending a string over the System.out stream. Guess what? There s also a System.in input stream! So we can create a reader (say, an InputStreamReader) that reads from System.in. Then, if we create a BufferedReader with this InputStreamReader, we ll be able to call readline to get a line of user input! Here s how to create such a reader: BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 4.2 Fun with Words Now that you know about streams, file readers, and file writers, it s time to combine them to create interactive programs! Combining multiple different readers and writers allows you to read from a file and write out to System.out, or vice versa. Task: Write a method, todocument, that repeatedly prompts the user for a word from the console, and writes those words to a file, with a space separating each word, until null/eof is reached. The method should just take in a BufferedWriter which will write to a file. Hint: You can use readline(), just like you did above! Task: Write a main method which takes in an argument denoting which file to write to. Then, it should create an appropriate writer (which writes to the file that was specified) and pass that in to todocument. Hint: Take a quick look at the Java InputStreamReader API. Hint: To tell the console that you re done sending input, you must send it an EOF : i.e., a signal that indicates the end of the stream. You do this by typing Ctrl-d. You must make your program stop accepting input after EOF. Note: Ctrl-d sometimes does not work in Eclipse. We are not sure why, but you may experience issues as you work on Search and other projects that rely on user input. For this reason, if you are having trouble with EOF in Eclipse, you should try running your program in the command line, where EOF will work. There is a guide on running from the command line on our course website. However, it is not strictly necessary for you to do this in order to get checked off; we understand this Eclipse issue is outside of your control. Note: Don t forget to be sure to print out an appropriate error message if a FileNotFoundException or IOException is thrown. 7
8 Note: For this group of tasks, you need not create a separate tester class; just run your methods and check to see that the effect was correct. You ve reached a checkpoint! Please call over a lab TA to review your work. 5 Files Task: Take a quick look at the Java File API. 5.1 Files and Directories A File (object) is used to represent a file on your system that your program can manipulate. One way to construct a File is: File myfile = new File("/course/cs0180/web/contents/labs/05javaIO-java.pdf"); Among others, every File has the following methods: ˆ length returns the size of the file in bytes. ˆ getname returns the name of the file. ˆ getpath returns the path to the file, including its name. ˆ getparent returns the directory containing the file as a String. This also includes the path to the directory. For example, if getparent were called on the file /course/cs0180/src/lab05/poem.txt, it would return /course/cs0180/src/lab05. ˆ getparentfile returns the directory containing the file as a File. This is exactly the same as getparent, but returns the directory as a File rather than a String. Here are some examples of the methods in use: java> File myfile = new File("/course/cs0180/web/content/labs/05javaIO-java.pdf") java> myfile.length() java> myfile.getname() "05javaIO-java.pdf" java> myfile.getpath() "/course/cs0180/web/content/labs/05javaio-java.pdf" java> myfile.getparent() "/course/cs0180/web/content/labs" java> myfile.getparentfile() /course/cs0180/web/content/labs 8
9 Observe that getparent returns a String, while getparentfile returns a File. The parent file is in fact a directory containing other files. Hence, a File can represent both files and directories. Here s how you construct a File that represents a directory, and list its contents: java> File mydir = new File("/course/cs0180/web/content") java> mydir.list() { "homeworks", "labs", "lectures", "projects" java> mydir.listfiles() { /course/cs0180/web/content/homeworks, /course/cs0180/web/content/labs, /course/cs0180/web/content/lectures, /course/cs0180/web/content/projects Observe that list() returns a list of Strings, whereas listfiles() returns a list of Files. You can test whether a File object is a file or a directory as follows: >java myfile.isfile() true java> myfile.isdirectory() false java> mydir.isfile() false java> mydir.isdirectory() true 5.2 Directory Listing The linux command ls lists all the files in a directory. With the arguments -a and -l, this command lists the files along with their size, owner, and most recent modification date. Task: Try out the ls command in a few of your own directories. Task: Write a method called ls that takes as input a directory name (as a String) and prints to standard output the names of all the files in that directory along with their lengths. You should print some informative error message if the input actually is not a directory! Task: Create a main method, which takes one argument and passes it into the ls method. Question: What does the File class length method return? That is, in what units does Java measure a file s length? Note: For this group of tasks, you need not create a separate tester class; just run your methods and check to see that the effect was correct. You ve reached a checkpoint! Please call over a lab TA to review your work. 9
10 5.3 Just for Fun: File Finder Task: Write a method which, given the name of a file and the name of a directory, searches that directory and its subdirectories for the file, and then prints out the full path of that file (if it exists). For example: java> FileFinder.findFile("Showdown.java", "/home/foo") "/home/foo/course/cs0180/projects/showdown/java/src/showdown/src/showdown.java" Your method should recursively search the directory tree, terminating either when it finds the file, or when it has searched the entire tree. If the file is not found, your method should print out an informative message, like this: java> FileFinder.findFile("Garbage.java", "/home/bar") "Garbage.java was not found in /home/bar" You should include a main method that expects the user to enter two arguments, which will then be passed into the findfile method. Then, you should print the result to the console. Hint: The FileFilter and FilenameFilter interfaces can be used to filter an array of File objects. For example, you might want to filter an array of File objects with the conditional test isdirectory. This can be done by including a sequence of statements like these in your code: File mydir = new File("/home/foo"); File[] directories = mydir.listfiles(new DirectoryFilter); Here, the DirectoryFilter must implement the FileFilter or the FilenameFilter interface. That is, it must implement an accept method, which returns a boolean. Hint: Click here to access the FileFilter and the FilenameFilter APIs. Once a lab TA signs off on your work, you ve finished the lab! Congratulations! Before you leave, make sure both partners have access to the code you ve just written. Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS18 document by filling out the anonymous feedback form: courses/cs018/feedback. 10
Lab 10: Sockets 12:00 PM, Apr 4, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 10: Sockets 12:00 PM, Apr 4, 2018 Contents 1 The Client-Server Model 1 1.1 Constructing Java Sockets.................................
More informationFile IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20
File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source
More informationJava Input/Output. 11 April 2013 OSU CSE 1
Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter
More informationLecture 11.1 I/O Streams
21/04/2014 Ebtsam AbdelHakam 1 OBJECT ORIENTED PROGRAMMING Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 2 Outline I/O Basics Streams Reading characters and string 21/04/2014 Ebtsam AbdelHakam
More informationCS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide
CS1092: Tutorial Sheet: No 3 Exceptions and Files Tutor s Guide Preliminary This tutorial sheet requires that you ve read Chapter 15 on Exceptions (CS1081 lectured material), and followed the recent CS1092
More informationLab 2: File Input and Output
Lab 2: File Input and Output This lab introduces how to handle files as both input and output. We re coming back to Tracery (which you implemented in Lab 1) with this assignment but instead of always reading
More informationInput, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003
Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data
More informationIntroduction Unit 4: Input, output and exceptions
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.
More information1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004
1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Section: You have 180 minutes to complete this exam. For coding questions, you do
More informationRemedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1
(remedial) Java anastasia.bezerianos@lri.fr I/O Anastasia Bezerianos 1 Input/Output Input Output Program We ve seen output System.out.println( some string ); Anastasia Bezerianos 2 Standard input/output!
More informationToday. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools
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
More informationCS11 Java. Fall Lecture 4
CS11 Java Fall 2014-2015 Lecture 4 Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the
More informationI/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O
I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)
More informationSpecial error return Constructors do not have a return value What if method uses the full range of the return type?
23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method
More information1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004
1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Solution Section: You have 180 minutes to complete this exam. For coding questions,
More informationIT101. File Input and Output
IT101 File Input and Output IO Streams A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents
More informationHomework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018 1 DIY Grep 2 2 Chaining Hash Tables 4 3 Hash Table Iterator 5 Objectives By the
More informationLesson 3: Accepting User Input and Using Different Methods for Output
Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program
More informationLab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018 Contents 1 Imperative Programming 1 1.1 Sky High Grades......................................
More information23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()
23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method
More informationByte and Character Streams. Reading and Writing Console input and output
Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates
More informationProject #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.
Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:
More informationPIC 20A Streams and I/O
PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read
More informationDarshan Institute of Engineering & Technology for Diploma Studies
Streams A stream is a sequence of data. In Java a stream is composed of bytes. In java, 3 streams are created for us automatically. 1. System.out : standard output stream 2. System.in : standard input
More information16-Dec-10. Consider the following method:
Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to
More informationSimple Java Input/Output
Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it
More informationLecture 5: Implementing Lists, Version 1
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 5: Implementing Lists, Version 1 Contents 1 Implementing Lists 1 2 Methods 2 2.1 isempty...........................................
More information09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.
CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics
More informationLecture 4: Exceptions. I/O
Lecture 4: Exceptions. I/O Outline Access control. Class scope Exceptions I/O public class Malicious { public static void main(string[] args) { maliciousmethod(new CreditCard()); } static void maliciousmethod(creditcard
More informationLecture 14: Exceptions 10:00 AM, Feb 26, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................
More informationHomework 2: Imperative Due: 5:00 PM, Feb 15, 2019
CS18 Integrated Introduction to Computer Science Fisler Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019 Contents 1 Overview of Generic/Parameterized Types 2 2 Double the Fun with Doubly-Linked Lists
More informationCS-152: Software Testing
CS-152: Software Testing Neal Holtschulte July 2, 2013 Software Testing Outline Terminology Assertions and when to use them Try-catch and when to use them What are Exceptions Further resources Practice
More informationName: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.
Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of
More informationProject #1 Computer Science 2334 Fall 2008
Project #1 Computer Science 2334 Fall 2008 User Request: Create a Word Verification System. Milestones: 1. Use program arguments to specify a file name. 10 points 2. Use simple File I/O to read a file.
More informationProject 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.
Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple movie data system. Milestones: 1. Use
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output
COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 30 April 4, 2018 I/O & Histogram Demo Chapters 28 HW7: Chat Server Announcements No penalty for late submission by tomorrow (which is a HARD deadline!)
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455
More informationData Structures. 03 Streams & File I/O
David Drohan Data Structures 03 Streams & File I/O JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.
More informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More informationExceptions and Working with Files
Exceptions and Working with Files Creating your own Exceptions. You have a Party class that creates parties. It contains two fields, the name of the host and the number of guests. But you don t want to
More informationVideo 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1
Video 2.1 Arvind Bhusnurmath SD1x-2 1 Topics Why is testing important? Different types of testing Unit testing SD1x-2 2 Software testing Integral part of development. If you ship a software with bugs,
More informationI/O STREAM (REQUIRED IN THE FINAL)
I/O STREAM (REQUIRED IN THE FINAL) STREAM A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents
More informationOverview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi
CSE 143 Overview Topics Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 2/3/2005 (c) 2001-5, University of Washington 12-1 2/3/2005 (c) 2001-5,
More informationLab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 2: Object-Oriented Design 12:00 PM, Jan 31, 2018 1 Terminology 1 2 Class Hierarchy Diagrams 2 2.1 An Example: Animals...................................
More informationPrinciples of Computer Science I
Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested
More informationBasic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)
I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:
More informationName: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.
Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning
More informationCS 251 Intermediate Programming Java I/O Streams
CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package
More informationCOMP-202 Unit 9: Exceptions
COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,
More informationBBM 102 Introduction to Programming II Spring Exceptions
BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom
More informationObject Oriented Programming. Week 9 Part 1 File I/O
Object Oriented Programming Part 1 File I/O Lecture Overview of Files Using Tests to learn Java Writing Text Files Reading Text Files 2 Overview of Files 3 Overview of Files How they are accessed: sequential:
More informationCIS 120 Final Exam May 3, Name (printed): Pennkey (login id):
CIS 120 Final Exam May 3, 2013 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing this
More informationCSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?
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? A stream is an abstraction representing the flow of data from one place to
More informationתוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת
תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת A Typical Program Most applications need to process some input and produce some output based on that input The Java IO package (java.io) is to make that possible
More informationQuestion 1. (2 points) What is the difference between a stream and a file?
CSE 143 Sp03 Midterm 2 Page 1 of 7 Question 1. (2 points) What is the difference between a stream and a file? Question 2. (2 points) Suppose we are writing an online dictionary application. Given a word
More informationOverview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp
Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 4/27/2004 (c) 2001-4, University of
More informationSoftware Practice 1 - File I/O
Software Practice 1 - File I/O Stream I/O Buffered I/O File I/O with exceptions CSV format Practice#6 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1 (43) / 38 2 / 38
More informationI/O Streams. Object-oriented programming
I/O Streams Object-oriented programming Outline Concepts of Data Streams Streams and Files File class Text file Binary file (primitive data, object) Readings: GT, Ch. 12 I/O Streams 2 Data streams Ultimately,
More informationHST 952. Computing for Biomedical Scientists Lecture 8
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java
More informationSri Vidya College of Engineering & Technology Question Bank
1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.
More informationActive Learning: Streams
Lecture 29 Active Learning: Streams The Logger Application 2 1 Goals Using the framework of the Logger application, we are going to explore three ways to read and write data using Java streams: 1. as text
More informationExceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,
More informationChapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,
More informationCS 200 File Input and Output Jim Williams, PhD
CS 200 File Input and Output Jim Williams, PhD This Week 1. WaTor Change Log 2. Monday Appts - may be interrupted. 3. Optional Lab: Create a Personal Webpage a. demonstrate to TA for same credit as other
More informationInheritance E, xc Ex eptions ceptions I/O
Inheritance, Exceptions, I/O ARCS Lab. Inheritance Very Very Basic Inheritance Making a Game public class Dude { public String name; public int hp = 100 public int mp = 0; } public void sayname() { System.out.println(name);
More informationCompile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.
(טיפול בשגיאות) Exception handling We learn that there are three categories of errors : Syntax error, Runtime error and Logic error. A Syntax error (compiler error) arises because a rule of the language
More information1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java
Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as
More informationExceptions. CSE 142, Summer 2002 Computer Programming 1.
Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»
More informationExceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.
Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented
More informationLab 7: OCaml 12:00 PM, Oct 22, 2017
CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More informationOverview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au
Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Sec. 19.1, Appendix A2 11/2/2003 (c) 2001-3,
More informationOverview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE
Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Sec. 19.1, Appendix A2 11/2/2003 (c) 2001-3,
More informationInput from Files. Buffered Reader
Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Files Two types: Text file and Binary file Text file (ASCII file) The file data contains only ASCII values
More informationIn this lab we will practice creating, throwing and handling exceptions.
Lab 5 Exceptions Exceptions indicate that a program has encountered an unforeseen problem. While some problems place programmers at fault (for example, using an index that is outside the boundaries of
More informationWeek 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O
Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file
More informationneeds to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine
Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as
More informationFile Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.
File Input/Output Tuesday, July 25 2006 CSE 1020, Summer 2006, Overview (1): Before We Begin Some administrative details Some questions to consider The Class Object What is the Object class? File Input
More informationOverview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE
CSE 143 Overview Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 10/20/2004 (c) 2001-4, University of
More informationAnswer Key. 1. General Understanding (10 points) think before you decide.
Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset
More informationExceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions
Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Winter 2015 Reading: Chapter 2, Relevant Links Some Material in these slides from J.F Kurose and K.W. Ross All material copyright
More informationAdministration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11
Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday
More informationDefensive Programming
Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 30 November 13, 2015 ExcepEons / IO Chapter 27 HW7: PennPals Chat Due: Tuesday, November 17 th Announcements Start today if you haven't already! Poll
More informationSoftware 1 with Java. Recitation No. 7 (Java IO) May 29,
Software 1 with Java Recitation No. 7 (Java IO) May 29, 2007 1 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating files Classes
More information7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)
116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.
More informationCSPP : Introduction to Object-Oriented Programming
CSPP 511-01: Introduction to Object-Oriented Programming Harri Hakula Ryerson 256, tel. 773-702-8584 hhakula@cs.uchicago.edu August 7, 2000 CSPP 511-01: Lecture 15, August 7, 2000 1 Exceptions Files: Text
More informationLab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018 Contents 1 Heapsort 2 2 Quicksort 2 3 Bubble Sort 3 4 Merge Sort 3 5 Mirror Mirror
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2018 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationLab 1: Introduction to Java
Lab 1: Introduction to Java Welcome to the first CS15 lab! In the reading, we went over objects, methods, parameters and how to put all of these things together into Java classes. It's perfectly okay if
More informationJAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object
http://www.tutorialspoint.com/java/java_file_class.htm JAVA - FILE CLASS Copyright tutorialspoint.com Java File class represents the files and directory pathnames in an abstract manner. This class is used
More informationExceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationIntroductory Programming Exceptions and I/O: sections
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationCSC 1214: Object-Oriented Programming
CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1214
More informationChapter 12. File Input and Output. CS180-Recitation
Chapter 12 File Input and Output CS180-Recitation Reminders Exam2 Wed Nov 5th. 6:30 pm. Project6 Wed Nov 5th. 10:00 pm. Multitasking: The concurrent operation by one central processing unit of two or more
More informationCISC 323 (Week 9) Design of a Weather Program & Java File I/O
CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming
More information