תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Lecture 3 Java Basics Lecture3.ppt.
CIS 234: File Input & Output Dr. Ralph D. Westfall May, 2007.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
1 Course Lectures Available on line:
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
Unix Environment Input Output 2  List Content (ls) ◦ ls (list current directory) ◦ ls –all (include hidden files/folders)  Make directory (mkdir) ◦
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
A stream is a sequence of data. A stream is a flowing sequence of characters.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed box. I/O gives your Java program access to your hard.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CIS 234: File Input & Output introduction. Data Storage Is Fundamental computers need to store data to work with it memory (RAM) is fast but transient.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
CPRG 215 Introduction to Object-Oriented Programming with Java Module 2- Using Java Built-in Classes Topic 2.6 Reading Input with java.io Produced by Harvey.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
Sequential files creation & writing
IO in java.
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Streams and File I/O.
University of Central Florida COP 3330 Object Oriented Programming
CHAPTER 5 JAVA FILE INPUT/OUTPUT
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
File Input and Output TOPICS File Input Exception Handling File Output.
Programming in Java Files and I/O Streams
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
שימוש במחלקות קיימות מחרוזות, קבצים, וקבלת קלט מהמשתמש
18 File i/o, Parsing.
Introduction to Computing Using Java
Files and Streams in Java
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
CS 240 – Advanced Programming Concepts
Presentation transcript:

תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 2 OOP and IO IO – Input/Output What is IO good for? In OOP services are united under Objects IO is also handled via predefined classes These objects are defined in the java.io package

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 3 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating files Classes for serializing objects

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 4 Online Resources JAVA API Specification: The Java Tutorial (Sun)

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 5 Handling IO Problems The result of an IO operation might be problematic Thus IO operations are defined as “throwing” exceptions We shall learn about it later this course Meanwhile, we just have to know how to handle it Try-catch block

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 6 The File Class Represents a file or directory pathname Performs basic file-system operations: removes a file: delete() creates a new directory: mkdir() checks if the file is writable: canWrite() No method to create a new file No direct access to file data Use file streams for reading and writing (later)

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 7 The File Class Example – get the current directory

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 8 The File Class Constructors Using a full pathname: File f = new File("/doc/foo.txt"); File dir = new File("/doc/tmp"); Using a pathname relative to the current directory of the Java interpreter: File f = new File(“foo.txt”); Note: System.getProperty(“user.dir”) returns the current directory of the interpreter

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 9 File Tests and Utilities File information: String getName() String getPath() String getAbsolutePath() String getParent() long lastModified() long length() File modification: boolean renameTo(File newName) boolean delete()

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 10 File Tests and Utilities Directory utilities: boolean mkdir() String[] list() File tests: boolean exists() boolean canWrite() boolean canRead() boolean isFile() boolean isDirectory() boolean isAbsolute()

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 11 The File Class Pathnames Pathnames are system-dependent "/doc/foo.txt" (UNIX format) "D:\doc\foo.txt" (Windows format) On Windows platform Java excepts path names either with '/' or '\‘ The system file separator is defined in: File.separator File.separatorChar

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 12 The File Class Directory Listing Printing all files and directories under the current directory: File file = new File("."); String[] files = file.list(); for (int i=0 ; i< files.length ; i++) { System.out.println(files[i]); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 13 The File Class Directory Listing (cont.) Print all files and directories under a given directory with ".txt" suffix File file = new File("C:/Assaf/Junk/"); String[] files = file.list(); for (int i=0 ; i<files.length ; i++) { if (files[i].endsWith(".txt")) System.out.println(files[i]); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 14 Streams A stream is a sequential flow of data Streams are one-way streets. Input streams are for reading Output streams are for writing Source Program Input Stream Target Program Output Stream read write File / Memory / Network…

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 15 Streams Usage Flow: open a stream while more information Read/write information close the stream All streams are automatically opened when created.

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 16 Streams There are two types of streams: Byte streams for reading/writing raw bytes Character streams for reading/writing text Class Name Suffix Convention: CharacterByte ReaderInputStream Input WriterOutputStream Output

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 17 Terminal I/O The System class provides references to the standard input, output and error streams: InputStream stdin = System.in; PrintStream stdout = System.out; PrintStream stderr = System.err;

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 18 The Scanner Class Breaks its input into tokens using a delimiter pattern (default: whitespace) er.html er.html The resulting tokens may then be converted into values Scanner s = new Scanner(System.in); int anInt = s.nextInt(); float aFloat = s.nextFloat(); String aString = s.next(); String aLine = s.nextLine(); How can we be sure that user will type-in the correct input?

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 19 Example - Scanner Set delimiters String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter(" *fish *"); while (s.hasNext()) System.out.println(s.next()); s.close();

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 20 Example - Scanner Input from the user Scanner s = new Scanner(System.in); System.out.println("enter line:"); while (s.hasNext()) System.out.println(s.next());

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 21 Example The whole loop Input from the user: Directory File suffix Output: all file that match the given suffix file-type at the given directory

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 22 Example The whole loop Scanner s = new Scanner(System.in); System.out.println(" Please enter directory and file-suffix: "); String dir = s.next(); String suffix = s.next(); File file = new File(dir); String[] files = file.list(); for (String filename : files) { if (filename.endsWith(suffix)) System.out.println(filename); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 23 Object Serialization A mechanism that enable objects to be: saved and restored from byte streams persistent (outlive the current process) Useful for: persistent storage sending an object to a remote computer

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 24 The File Class API, throws Why didn’t we have to use try-catch? Let’s check the API: File file = new File("."); String[] files = file.list(); for (int i=0 ; i< files.length ; i++) { System.out.println(files[i]); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 25 copy-paste to eclipse … Example – get the current directory import java.io.File; public class Test { public static void main (String [] args){ File dir1 = new File ("."); File dir2 = new File (".."); System.out.println(System.getProperty("user.dir")); try { System.out.println ("Current dir : " + dir1.getCanonicalPath()); System.out.println ("Parent dir : " + dir2.getCanonicalPath()); } catch(Exception e) { e.printStackTrace(); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 26 The File Class Directory Listing (cont.) Can’t we use one of File methods for that? File file = new File("C:/Assaf/Junk/"); String[] files = file.list(new SuffixFileFilter(".jpg")); for (int i=0 ; i<files.length ; i++) { System.out.println(files[i]); }

תכנות מתקדם בשפת Java אוניברסיטת תל אביב 27 The File Class Constructors (cont) File f = new File("/doc","foo.txt"); File dir = new File("/doc"); File f = new File(dir, "foo.txt"); A File object can be created for a non- existing file or directory Use exists() to check if the file/dir exists directory pathname file name