תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
Java I/O and Java Networking (Client Side) Yoshi.
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.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
1 Text File I/O 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.
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
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
CIS 068 JAVA I/O: Streams and Files. CIS 068 I/O Usual Purpose: storing data to ‘nonvolatile‘ devices, e.g. harddisk Classes provided by package java.io.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
Two Ways to Store Data in a File Text format Binary format.
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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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,
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.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
I/O in Java Dennis Burford
The Java I/O Classes and Interfaces cont’d
File IO Basics By Dan Fleck Coming up: Data Streams.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
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.
Two Ways to Store Data in a File  Text format  Binary format.
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.
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.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
CSC1351 Class 6 Classes & Inheritance.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
IO in java.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Strings and File I/O.
12: The Java I/O System stream model.
I/O Basics.
Java’s Hierarchy Input/Output Classes and Their Purpose
Java Programming Course
JAVA IO.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
Reading and Writing Text Files
CSC 143 Java Streams.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Web Design & Development Lecture 8
Java Basics Introduction to Streams.
EEC 484/584 Computer Networks
Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
David Davenport Spring 2005
Presentation transcript:

תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams, תוכנה 1 אוניברסיטת תל אביב תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams, קוראים וכותבים, והשימוש בהם לצורך עבודה עם קבצים

תוכנה 1 - אוניברסיטת תל אביב Input/Output in Java פעולות קלט-פלט הן רכיב מרכזי בכל שפת תכנות, והן מאפשרות לתוכנית לקבל (קלט) או לשלוח (פלט) נתונים מ\אל משאב חיצוני. אפשרויות פלט בהם נתקלנו עד עתה: הדפסה למסך באמצעות זרם הפלט הסטנדרטי System.out אפשרויות קלט בהם נתקלנו עד עתה: קבלת ארגומנטים בשורת הפקודה (ניתנים בעת הרצת התוכנית). קריאת נתונים המוקלדים ע"י המשתמש במסך הקונסול באמצעות זרם הקלט הסטנדרטי System.in (תוך שימוש ב-Scanner). קריאת נתונים מקובץ טקסט (תוך שימוש ב-Scanner). היום נלמד מהם למעשה זרמי קלט\פלט, ונכיר מחלקות המאפשרות ביצוע פעולות קלט-פלט ברמות שונות של תחכום. תוכנה 1 - אוניברסיטת תל אביב

המשימה במערכות הפעלה שונות נעשה שימוש בתווי בקרה שונים עבור ירידת שורה (newline): ב-UNIX/Linux – \n (Line Feed) ב-Windows - \r\n (Carriage Return + Line Feed) יכולות להתעורר בעיות... נרצה לכתוב תכנית לתיקון קבצי טקסט בדוגמא – תיקון מ-UNIX ל-Windows windows: Linux: דוגמא לקובץ שנכתב ב linux ונפתח ב windows תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב תכנון פתרון ארגומנטים: קובץ קלט וקובץ פלט קריאה מקובץ הקלט כבר ראינו דוגמא עם Scanner, היום נראה דרכים אחרות החלפת ירידת השורה יצירת קובץ הפלט כתיבת הפלט לא בהכרח בסדר הזה... IO! תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב נושאים נוספים בתרגול היום נזכיר את שני הנושאים הבאים בקצרה, ונפרט עליהם בשבועות הבאים: היררכיית מחלקות ה-IO ב-Java טיפול בשגיאות זמן ריצה (נפוצות במיוחד בעבודה עם IO) תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב קלט ופלט בג'אווה משאבי מידע: קבצים, console, רשת, זיכרון, DB, תכניות אחרות... התכנית שלנו צריכה לדעת איך לתרגם את הביטים לעצמים \ טיפוסים פרימיטיביים ובחזרה Tutorial מומלץ: http://docs.oracle.com/javase/tutorial/essential/io/index.html תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב זרמים (Streams) קבוצה של טיפוסים שיודעים לקרוא ולכתוב ממשאבים בצורה סדרתית קוראים \ כותבים בתים (bytes) הזרימה היא תמיד חד-כיוונית Input Streams – לקריאה Output Streams – לכתיבה לדוגמא FileOutputStream לקובץ כותב תוכנה 1 - אוניברסיטת תל אביב

שימוש אופייני בזרמי קלט ופלט כל הזרמים נפתחים עם יצירתם FileOutputStream – אפילו יוצר קובץ חדש פתיחת זרם יכולה לגרום לזריקת חריג (Exception). יש לסגור את הזרמים בגמר השימוש כדי לאפשר שחרור משאבים. שימוש סטנדרטי (פסאודו קוד): קריאת נתונים מזרם קלט כתיבת נתונים לזרם פלט Open input stream While can read read unit do something Close stream Open output stream While has data to write write unit Close stream תוכנה 1 - אוניברסיטת תל אביב

דוגמאות לזרמים שימושיים FileInputStream FileOutputStream קריאה\כתיבה של בתים (Bytes) מקבצים BufferedInputStream BufferedOutputStream קריאה\כתיבה של בתים תוך שימוש במאגר מובנה FileReader, FileWriter קריאה\כתיבה של תווים מקבצים: DataInputStream DataOutputStream קריאה\כתיבה של טיפוסים פרימיטיביים ומחרוזות (בדומה ל-Scanner): https://docs.oracle.com/javase/tutorial/esse ntial/io/

דוגמא 1 – שימוש ב- File IO Streams public class ByteUnixToWindows { public static void main(String[] args) throws IOException { File fromFile = new File(args[0]); FileInputStream fis = new FileInputStream(fromFile); int readByte; while ((readByte = fis.read()) != -1) { System.out.write(readByte); } System.out.println(); fis.close(); ארגומנט: המסלול לקובץ קוראים byte בכל פעם. המתודה read מחזירה int כדי לסמן את סוף הקובץ ב- -1 כרגע רק כותבים ל-console, לא תיקנו את הבעיה! תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב הפתרון לא יעיל! נרצה לקרוא הרבה בתים בבת אחת נוסיף כתיבה לקובץ תוך שימוש ב-FileOutputStream נקבל כארגומנט שני את המסלול לקובץ הפלט תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב דוגמא 2 – מערך בתים public class ByteArrayUnixToWindows { public static void main(String[] args) throws IOException { File fromFile = new File(args[0]); FileInputStream fis = new FileInputStream(fromFile); File toFile = new File(args[1]); FileOutputStream fos = new FileOutputStream(toFile); byte[] readBytes = new byte[1000]; int numRead; while ((numRead = fis.read(readBytes)) != -1) { fos.write(readBytes, 0, numRead); } fis.close(); fos.close(); numRead שווה למס' הבתים שקראנו בפועל, לכן זה גם מס' הבתים שנכתוב כן: כותבים לקובץ עדין לא: מתקנים את newline תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב עבודה עם טקסט הקלט והפלט שלנו הם קבצי טקסט תיקון newline עם bytes – אפשרי, אבל לא נוח! היינו רוצים לעבוד עם מחרוזות ו-characters תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב Reader & Writer מחלקות שקוראות וכותבות רצפים של characters ממשאבים. לדוגמא: FileReader, FileWriter בעיה פוטנציאלית: Characters בג'אווה הם עם קידוד מסויים (UTF-16) מה אם לקבצים שלנו יש קידוד אחר? תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב והפתרון... בד"כ Java פותרת את הבעיה בעצמה! קידוד ברירת מחדל מוגדר עבור מערכת ההפעלה Java מתרגמת אותו ל-characters שלה לעתים ניתן להגדיר מה הקידוד הדרוש new InputStreamReader(is, Charset.forName("UTF-8")); 0000000001001000 0000000001100101 0000000001101100 'H' 'e' 'l' 01001000 01100101 01101100 H e l תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב דוגמא 3 – Reader & Writer public class CharacterUnixToWindows { public static void main(String[] args) throws IOException { File fromFile = new File(args[0]); FileReader fReader = new FileReader(fromFile); File toFile = new File(args[1]); FileWriter fWriter = new FileWriter(toFile); char[] charRead = new char[1000]; int numRead; while ((numRead = fReader.read(charRead)) != -1) { String string = new String(charRead, 0, numRead); String windowsString = string.replaceAll("\n", "\r\n"); fWriter.write(windowsString); } fReader.close(); fWriter.close(); הפתרון לא היה עובד בהמרה הפוכה (windows ל linux)! למה? תוכנה 1 - אוניברסיטת תל אביב

Stream Wrappers קיימים זרמים אשר "עוטפים" זרמים אחרים ומוסיפים להם פונקציונליות לדוגמא, רוצים לקרוא מקובץ (FileReader) אבל שורה בכל פעם (BufferedReader) כשניצור את הקורא השני, נעביר לו את הראשון כארגומנט. new BufferedReader(new FileReader(file)) String (line) BufferedReader file FileReader char[] תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב איך זה עובד? אנחנו נעבוד עם הזרם העוטף החיצוני ביותר (BufferedReader בדוגמא) נשלח לו מהקוד בקשות קריאה או כתיבה כל זרם עוטף מחליט מתי לשלוח בקשת קריאה\כתיבה לזרם הנעטף על-ידו ומבצע עיבוד על המידע לפני שהוא מעביר אותו הלאה עלינו רק לדאוג לחבר את הזרמים בצורה נכונה תוכנה 1 - אוניברסיטת תל אביב

Stream Wrappers – דוגמא נוספת רוצים להדפיס לOutputStream נתון. OutputStreamWriter מאפשר לנו לעטוף Stream ב-Writer )וגם לבחור את הקידוד, כפי שראינו עם InputStreamReader) PrintWriter מאפשר הדפסה בדומה ל-System.out new PrintWriter(new OutputStreamWriter(givenOutputStream)) PrintWriter char[] OutputStreamWriter byte[] OutputStream תומך במתודות printf ו-format תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב דוגמא 4 – Buffered public class BufferedUnixToWindows { public static void main(String[] args) throws IOException { File fromFile = new File(args[0]); BufferedReader bufferedReader = new BufferedReader(new FileReader(fromFile)); File toFile = new File(args[1]); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(toFile)); String line; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line + "\r\n"); } bufferedReader.close(); bufferedWriter.close(); readLine() "שובר שורות" לפי כל הסוגים האפשריים של newline בכתיבה נוסיף את ירידת השורה הרצויה close() סוגר גם את כל הזרמים הנעטפים תוכנה 1 - אוניברסיטת תל אביב

סיכום הטכניקות שהוצגו בדוגמאות 1-4 מחלקות IO רלבנטיות תיאור 1 FileInputStream קריאה של בית בודד מקובץ. הבית מוחזר כ-int המאחסן מספר בטווח 0-255 או -1 במקרה של הגעה לסוף הקובץ. כתיבה של בתים לזרם הפלט הסטנדרטי (למסך). 2 FileOutputStream קריאה של הרבה בתים בבת אחת לתוך מערך מסוג byte[] (שמשמש כמעין מאגר ידני המשפר ביצועים בהשוואה לקריאה של בית בודד בכל פעם). כתיבה של מערך בתים לקובץ. 3 FileReader FileWriter קריאה של הרבה תווים בבת אחת לתוך מערך מסוג char[]. הקידוד מבתים לתווים נעשה אוטומטית ע"י ה-Reader. המרה ממערך תווים למחרוזת, עיבודה, וכתיבתה לקובץ (המרה ממחרוזת לבתים נעשית ע"י ה-Writer). 4 BufferedReader BufferedWriter קריאה של תווים תוך שימוש במאגר מובנה המשפר ביצועים. קריאה של שורות טקסט (זיהוי \n) מהקובץ כמחרוזות איתן קל לעבוד.

בחירת זרם לפי סוג הקובץ סוג הקובץ סוג הזרם (כתיבה) קובץ טקסט קצר תוכנה 1 אוניברסיטת תל אביב בחירת זרם לפי סוג הקובץ סוג הקובץ סוג הזרם (כתיבה) קובץ טקסט קצר new FileReader(fileName) קובץ טקסט ארוך new BufferedReader(new FileReader(fileName)) קובץ בינארי קצר new FileInputStream(fileName) קובץ בינארי ארוך new BufferedInputStream(new FileInputStream(fileName)) סוג הקובץ סוג הזרם (קריא) קובץ טקסט קצר new FileWriter(fileName) קובץ טקסט ארוך new BufferedWriter(new FileWriter(fileName)) קובץ בינארי קצר new FileOutputStream(fileName) קובץ בינארי ארוך new BufferedOutputStream(new FileOutputStream(fileName))

איפה נכנס ה Scanner לתמונה? תוכנה 1 אוניברסיטת תל אביב איפה נכנס ה Scanner לתמונה? בתרגול שעבר ראינו דוגמת שימוש ב Scanner לקריאה מקבצי טקסט. מה עדיף – Scanner או FileReader יחד עם BufferedReader? ל Scanner יש Buffer, אבל הוא קטן יותר מה Buffer של ה BufferedReader. גודל ה Buffer הוא רלוונטי כשאשר נעבור עם קבצים גדולים ונרצה לחסוך גישות לדיסק. Scanner מאפשר פעולות עיבוד מתוחכמות על קובץ הטקסט אותו אנו קוראים. בעוד שה BufferedReader מחזיר מחרוזות בלבד, ה Scanner יכול לחץ טיפוסים פרימיטיביים כמו int, boolean וכו'. שימושי כאשר אנחנו רוצים לבצע המרות תוך כדי הקריאה מהקובץ.

תוכנה 1 - אוניברסיטת תל אביב אבל... אין דרך פשוטה יותר? קריאה וכתיבה לקבצים הן פעולות סטנדרטיות דיון: אולי צריך BufferedFileReader ו- BufferedFileWriter? היינו רוצים לקרוא את כל הקובץ בפקודה אחת החל מ-Java SE 7.0 יש דרך לעשות זאת! תוכנה 1 - אוניברסיטת תל אביב

המחלקה java.nio.file.Files http://docs.oracle.com/javase/8/docs/api/index.html?java/ nio/file/Files.html מכילה שירותים שימושיים לעבודה עם קבצים עובדת עם עצמים מסוג java.nio.file.Path שמתאימים למסלולי קבצים (בדומה ל-java.io.File). המחלקה המשלימה java.nio.file.Paths מכילה שירותים שימושיים עבור מסלולי קבצים. Paths.get("examples","example.txt") יחזיר אובייקט מסוג Path שמתאים למסלול הקובץ היחסי examples/example.txt תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב המחלקה Files - דוגמאות copy – העתקת קבצים ובדומה move, delete isDirectory, isReadable, isWritable, isExecutable, exists – מחזירות פרטים שונים לגבי ה-Path readAllBytes – קריאת כל הקובץ בבת אחת. אין צורך לפתוח ולסגור זרמים מתאים רק לקבצים קטנים יחסית! תוכנה 1 - אוניברסיטת תל אביב

דוגמא 5 – שימוש במחלקה Files public class FilesUnixToWindows { public static void main(String[] args) throws IOException { String fromFile = args[0]; String toFile = args[1]; byte[] allBytes = Files.readAllBytes(Paths.get(fromFile)); String string = new String(allBytes); String windowsString = string.replaceAll("\n", "\r\n"); Files.write(Paths.get(toFile), windowsString.getBytes()); } תוכנה 1 - אוניברסיטת תל אביב

תוכנה 1 - אוניברסיטת תל אביב לסיכום ראינו דרכים שונות לעבודה עם קלט ופלט זרמים, קוראים וכותבים, Scanner, Files בעיקר עבודה עם קבצים, אבל לא רק! נשתמש בהם לפי הצורך האם יש צורך בעוד זרמים? שיקולי יעילות ומודולריות לעומת נוחות תוכנה 1 - אוניברסיטת תל אביב

טבלת זרמים שימושיים – בתים טבלת זרמים שימושיים – בתים Output streams Input streams כתיבה לקובץ FileOutputStream קריאה מקובץ FileInputStream (עוטף) כנ"ל לכתיבה BufferedOutputStream (עוטף) קריאה יותר יעילה דרך buffer BufferedInputStream DataOutputStream (עוטף) קריאת טיפוסים פרימיטיביים DataInputStream (עוטף) מאפשר "החזרה" של חלק מהבתים ל-Stream הנעטף PushbackInputStream עוטף רצף של Streams: קורא מאחד, אח"כ מהשני וכו' SequenceInputStream תוכנה 1 - אוניברסיטת תל אביב

טבלת זרמים שימושיים - תווים Writers Readers כתיבה לקובץ FileWriter קריאה מקובץ FileReader כנ"ל לכתיבה StringWriter קריאה ממחרוזת StringReader (עוטף) כנ"ל לכתיבה BufferedWriter (עוטף) קריאה יותר יעילה דרך buffer, מאפשר קריאת שורה BufferedReader OutputStreamWriter עוטף Stream. מאפשר בחירת קידוד InputStreamReader (עוטף) פעולות הדפסה שונות (println למשל) PrintWriter (עוטף) מאפשר לדעת כמה שורות קראנו ע"י getLineNumber LineNumberReader תוכנה 1 - אוניברסיטת תל אביב