Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?



Similar documents
D06 PROGRAMMING with JAVA

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Object-Oriented Programming in Java

Lecture J - Exceptions

Creating a Simple, Multithreaded Chat System with Java

D06 PROGRAMMING with JAVA

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Introduction to Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Course Intro Instructor Intro Java Intro, Continued

CS 111 Classes I 1. Software Organization View to this point:

Files and input/output streams

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

13 File Output and Input

CS 121 Intro to Programming:Java - Lecture 11 Announcements

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

AP Computer Science File Input with Scanner

Using Files as Input/Output in Java 5.0 Applications

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Reading Input From A File

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

AP Computer Science Java Subset

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

CS506 Web Design and Development Solved Online Quiz No. 01

Chapter 2: Elements of Java

Event-Driven Programming

public static void main(string[] args) { System.out.println("hello, world"); } }

Sample CSE8A midterm Multiple Choice (circle one)

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

What are exceptions? Bad things happen occasionally

Simple Java I/O. Streams

Topic 11 Scanner object, conditional execution

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Building Java Programs

Java Programming Language

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Chapter 2 Introduction to Java programming

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Building a Multi-Threaded Web Server

Building Java Programs

Explain the relationship between a class and an object. Which is general and which is specific?

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Mail User Agent Project

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Quick Introduction to Java

Lesson: All About Sockets

Software Construction

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Crash Course in Java

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Building Java Programs

Java Programming Fundamentals

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

6.1. Example: A Tip Calculator 6-1

INPUT AND OUTPUT STREAMS

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Using NetBeans IDE to Build Quick UI s Ray Hylock, GISo Tutorial 3/8/2011

WRITING DATA TO A BINARY FILE

Week 1: Review of Java Programming Basics

Visit us at

Division of Informatics, University of Edinburgh

AP Computer Science Static Methods, Strings, User Input

Install Java Development Kit (JDK) 1.8

Amazon EC2 KAIST Haejoon LEE

J a v a Quiz (Unit 3, Test 0 Practice)

Introduction to Java. CS 3: Computer Programming in Java

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

The following program is aiming to extract from a simple text file an analysis of the content such as:

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

What is an I/O Stream?

No no-argument constructor. No default constructor found

Java Application Developer Certificate Program Competencies

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

JAVA ARRAY EXAMPLE PDF

JAVA - FILES AND I/O

Input / Output Framework java.io Framework

CS 106 Introduction to Computer Science I

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Chapter 3. Input and output. 3.1 The System class

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Java Interview Questions and Answers

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Programming Languages CIS 443

Moving from CS 61A Scheme to CS 61B Java

Homework/Program #5 Solutions

Stream Classes and File I/O

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Fundamentals of Java Programming

Capabilities of a Java Test Execution Framework by Erick Griffin

Software Development in Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Transcription:

Chapter 11 Question R11.1: R11.1 What happens if you try to open a file for reading that doesn t exist? What happens if you try to open a file for writing that doesn t exist? The system throws an IOException in each situation. Question R11.2. R11.2 What happens if you try to open a file for writing, but the file or device is write-protected (sometimes called read-only)? Try it out with a short test program. IOException might occur if you are trying to create a file on a disk that is "write-protected," meaning that it cannot be modified. But you can open a file in read-only mode. Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat? A backslash like is used in a file path can't be used directly in a Java String. Java uses the backslash to mean the next character means something special. Doubling the backslash in Java indicates that the next character (the second backslash) should be inserted into the String. Question R11.4. R11.4 What is a command line? How can a program read its command line arguments? A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter: C:\>java Sort friends.txt When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt". Question R11.7. R11.7 What is the difference between throwing an exception and catching an exception? Before catching an exception it is must to be thrown first. This means that there should be a code somewhere in the program that could catch the exception. We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object. Throwable objects are instances of any subclass of the Throwable class.

Question R11.8. R11.8 What is a checked exception? What is an unchecked exception? Is a NullPointer-Exception checked or unchecked? Which exceptions do you need to declare with the throws reserved word? Unchecked exceptions: Represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." Are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException. A method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so) Checked exceptions: Represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files) Are subclasses of Exception A method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow) It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked). Question R11.10. R11.10 When your program executes a throw statement, which statement is executed next? After running the exception handler, the interpreter continues execution at the statement immediately following the handler code. Question R11.12. R11.12 What can your program do with the exception object that a catch clause receives? The variable exception contains a reference to the exception object that was thrown. The catch clause can analyze that object to find out more details about the failure. For example, you can get a printout of the chain of method calls that lead to the exception, by calling exception.printstacktrace() In these sample catch clauses, we merely inform the user of the source of the problem. A better way of dealing with the exception would be to give the user another chance to provide a correct input.

Question R11.14. R11.14 What kind of values can you throw? Can you throw a string? An integer? Only instances of subclasses of throwable can be used in conjunction with the throw keyword. In java all exceptions and errors are subclasses of throwable. Question R.11.16. R11.16 What happens when an exception is thrown, the code of a finally clause executes, and that code throws an exception of a different kind than the original one? Which one is caught by a surrounding catch clause? Usually, when you work with streams, sockets, database connections and that sort of things, you should 'think safe'. The usual approach is indeed to put a try/catch clause inside the finally clause, so that it won't crash your app if something goes wrong while closing the stream. Don't worry about your code being a bit cluttered: safety has a price. It is sometime necessary to put a try catch block within a catch or finally block. A Finally block will be executed after a try block if no exception has been thrown or after a catch if an exception was thrown. This means that a finally block can be used as 'clean up' - a place to close files or connections etc., whether an exception is thrown or not. Question R11.17. R11.17 Which exceptions can the next and nextint methods of the Scanner class throw? Are they checked exceptions or unchecked exceptions? int nextint(): Returns the next token as an int. If the next token is not an integer, InputMismatchException is thrown. String next(): Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If not token exists, NoSuchElementException is thrown. Both are checked exceptions. Question R11.18. R11.18 Suppose the code in Quality Tip 11.3 on page 489 had been condensed to a single try/catch/finally statement: PrintWriter out = new PrintWriter(filename); Try Write output catch (IOException exception) Handle exception Finally out.close(); What is the disadvantage of this version? (Hint: What happens when the PrintWriter

constructor throws an exception?) Why can t you solve the problem by moving the declaration of the out variable inside the try block? The instruction out.close() can throws an exception that not be catch. Why can t you solve the problem by moving the declaration of the out variable inside the try block? Because the problem can appear again. Question P11.1 P11.1 Write a program that asks a user for a file name and prints the number of characters, words, and lines in that file. import java.io.filereader; import java.io.ioexception; public class FileAnalyzer public static void main(string[] args) throws IOException System.out.println("Filename: "); Scanner in = new Scanner(System.in); String name = in.nextline(); FileCounter counter = new FileCounter(); FileReader reader = new FileReader(name); Scanner filein = new Scanner(reader); counter.read(filein); filein.close(); System.out.println("Characters: " + counter.getcharactercount()); System.out.println("Words: " + counter.getwordcount()); System.out.println("Lines : " + counter.getlinecount()); A class to count the number of characters, words, and lines in files. public class FileCounter private int numwords; private int numlines; private int numcharacters; public FileCounter() this.numwords=0; this.numlines=0; this.numcharacters=0; Processes an input source and adds its character, word, and line counts to this counter. @param in the scanner to process public void read(scanner in) String s;

while(in.hasnextline()) this.numlines++; this.numwords++; s=in.nextline(); for(int i=0;i<s.length();i++) if(s.charat(i)==' ')this.numwords++; else this.numcharacters++;; Gets the number of words in this counter. @return the number of words public int getwordcount() return numwords; Gets the number of lines in this counter. @return the number of lines public int getlinecount() return numlines; Gets the number of characters in this counter. @return the number of characters public int getcharactercount() return numcharacters; Question P11.2. P11.2 Write a program that asks the user for a file name and counts the number of characters, words, and lines in that file. Then the program asks for the name of the next file. When the user enters a file that doesn t exist, the program prints the total counts of characters, words, and lines in all processed files and exits. import java.io.filereader; import java.io.ioexception; public class FileAnalyzer public static void main(string[] args) throws IOException Scanner in = new Scanner(System.in); FileCounter counter = new FileCounter(); int nfiles=0; boolean Fail=false; while(!fail) try

System.out.println("Filename: "); String name = in.nextline(); FileReader reader = new FileReader(name); Scanner filein = new Scanner(reader); counter.read(filein); filein.close(); nfiles++; System.out.println("Characters: " + counter.getcharactercount()); System.out.println("Words: " + counter.getwordcount()); System.out.println("Lines : " + counter.getlinecount()); catch(exception e) System.out.println("" + nfiles + " Files read..."); System.out.println("Total Characters: " + counter.gettotalcharactercount()); System.out.println("Total Words: " + counter.gettotalwordcount()); System.out.println("Total Lines : " + counter.gettotallinecount()); Fail=true; A class to count the number of characters, words, and lines in files. public class FileCounter private int numwords; private int numlines; private int numcharacters; private int numtotalwords; private int numtotallines; private int numtotalcharacters; public FileCounter() this.numwords=0; this.numlines=0; this.numcharacters=0; this.numtotalwords=0; this.numtotallines=0; this.numtotalcharacters=0; Processes an input source and adds its character, word, and line counts to this counter. @param in the scanner to process public void read(scanner in) String s; this.numwords=0; this.numlines=0; this.numcharacters=0; while(in.hasnextline()) this.numlines++; this.numwords++; s=in.nextline(); for(int i=0;i<s.length();i++) if(s.charat(i)==' ')this.numwords++; else this.numcharacters++;;

this.numtotallines+=this.numlines; this.numtotalcharacters+=this.numcharacters; this.numtotalwords+=this.numwords; Gets the number of words in this counter. @return the number of words public int getwordcount() return numwords; public int gettotalwordcount() return numtotalwords; Gets the number of lines in this counter. @return the number of lines public int getlinecount() return numlines; public int gettotallinecount() return numtotallines; Gets the number of characters in this counter. @return the number of characters public int getcharactercount() return numcharacters; public int gettotalcharactercount() return numtotalcharacters; Question P11.4. P11.4 Write a program that concatenates the contents of several files into one file. For example, java CatFiles chapter1.txt chapter2.txt chapter3.txt book.txt makes a long file, book.txt, that contains the contents of the files chapter1.txt, chapter2.txt, and chapter3.txt. The output file is always the last file specified on the command line. import java.io.*; public class ConcatenatedFiles static public void main(string arg[]) throws java.io.ioexception PrintWriter pw = new PrintWriter(new FileOutputStream(arg[arg.length-1])); for (int nfile = 0; nfile < arg.length-1; nfile++)

System.out.println("Processing " + arg[nfile] + "... "); BufferedReader br = new BufferedReader(new FileReader(arg[nFile])); String line = br.readline(); while (line!= null) pw.println(line); line = br.readline(); br.close(); pw.close(); System.out.println("All files have been concatenated into " + arg[arg.length-1]); Question P11.5. P11.5 Write a program Find that searches all files specified on the command line and prints out all lines containing a reserved word. For example, if you call java Find ring report.txt address.txt Homework.java then the program might print report.txt: has broken up an international ring of DVD bootleggers that address.txt: Kris Kringle, North Pole address.txt: Homer Simpson, Springfield Homework.java: String filename; The reserved word is always the first command line argument import java.io.bufferedreader; import java.io.fileoutputstream; import java.io.filereader; import java.io.printwriter; public class P11_5 // this method return true if Pattern is substring of Line public static boolean hasstring(string Line,String Pattern) boolean has=false; String Temp; for(int i=0;i<(line.length()-pattern.length()+1);i++) Temp=Line.substring(i, i+pattern.length()); if(temp.equals(pattern)) has=true;i=line.length()-pattern.length()+1; return has; static public void main(string arg[]) throws java.io.ioexception String Pattern = arg[0]; for (int nfile = 1; nfile < arg.length; nfile++) line); System.out.println("Processing " + arg[nfile] + "... "); BufferedReader br = new BufferedReader(new FileReader(arg[nFile])); String line = br.readline(); if(hasstring(line,pattern)) System.out.println(arg[nFile]+ ": " + line); while (line!= null) line = br.readline(); if(hasstring(line,pattern)) System.out.println(arg[nFile]+ ": " + br.close();

Question 11.11. P11.6 Write a program that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. A word list is available on most UNIX systems in the file /usr/dict/words. (If you don t have access to a UNIX system, your instructor should be able to get you a copy.) The program should print out all words that it cannot find in the word list. import java.io.bufferedreader; import java.io.file; import java.io.filereader; public class P11_6 // This method return true if Word is in Dictionary File public static boolean iscorrect(string Dictionary,String Word)throws java.io.ioexception boolean is=false; BufferedReader br = new BufferedReader(new FileReader(Dictionary)); String line = br.readline(); if(line.equals(word)) is=true; while (line!= null) line = br.readline(); if(line.equals(word)) is=true; br.close(); return is; static public void main(string arg[]) throws java.io.ioexception String Dictionary = arg[0]; String File = arg[1]; System.out.println("Processing " + File + "... "); Scanner sc = new Scanner(new File(File)); String Word; while(sc.hasnext()) Word = sc.next(); if(!iscorrect(dictionary,word)) System.out.println(Word); sc.close(); Question P11.14. P11.14 Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user a second chance to enter the value. After two chances, quit reading input. Add all correctly specified values and print the sum when the user is done entering data. Use exception handling to detect improper inputs. import java.util.inputmismatchexception; public class P11_14 public static void main(string Args[]) boolean flaga=true; boolean flagb=true; float num; float sum=0; Scanner input = new Scanner(System.in); while (flaga)

try while (flagb) try System.out.print("Value: "); num = input.nextfloat(); sum += num; catch (InputMismatchException e) System.out.println("Input error. Try again."); flagb = false; System.out.print("Value: "); num = input.nextfloat(); sum += num; flagb = true; catch (InputMismatchException f) System.out.println("Input error. Try again"); flaga = false; System.out.println(sum);