Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

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.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
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
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
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.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Java I/O and Java Networking (Client Side) Yoshi.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Java I/O Input: information brought to program from an external source
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.
Loops, Methods, Classes Loops, Methods, Using API Classes, Exceptions SoftUni Team Technical Trainer Software University
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
Files and Streams File Types, Using Streams, Manipulating Files SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Bogomil Dimitrov Technical Trainer Software.
Applications Development Input and Output in Java Topics covered: Some input-output capabilities of Java Example input code Java.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
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.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
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.
1 OOP Lecture 17 I/O and Graphics Signe Ellegård Borch Carsten Schuermann IT University Copenhagen.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
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.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
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 Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming Language (3) - Input/Output Stream –
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
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.
The Java IO System Different kinds of IO Different kinds of operations
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Files and Streams The material in this chapter is not tested on the AP CS exams.
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
Using Streams, Files, Serialization
I/O Basics.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Stream Oriented I/O Computer Programming II Dr. Tim Margush
Files and Streams in Java
Web Design & Development Lecture 8
Java Basics Introduction to Streams.
David Davenport Spring 2005
Presentation transcript:

Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical Trainer Software University

2 1.Exception Handling Basics 2.Stream types  java.io package  How to choose the correct class? 3.Readers and Writers 4.Serialization  Saving custom objects Table of Contents

Exception Handling Basics Catch and Throw Exceptions

4  In Java exceptions are handled by the try-catch-finally construction  catch blocks can be used multiple times to process different exception types Handling Exceptions try { // Do some work that can raise an exception // Do some work that can raise an exception } catch (SomeException ex) { // Handle the caught exception // Handle the caught exception } finally { // This code will always execute // This code will always execute}

5 Handling Exceptions – Example public static void main(String[] args) { String str = new Scanner(System.in).nextLine(); String str = new Scanner(System.in).nextLine(); try { try { int i = Integer.parseInt(str); int i = Integer.parseInt(str); System.out.printf( System.out.printf( "You entered a valid integer number %d.\n", i); "You entered a valid integer number %d.\n", i); } catch (NumberFormatException nfex) { catch (NumberFormatException nfex) { System.out.println("Invalid integer number: " + nfex); System.out.println("Invalid integer number: " + nfex); }}

6  A method in Java could declare " throws SomeException "  This says "I don't care about SomeException ", please re-throw it The "throws …" Declaration public static void copyStream(Reader Reader, Writer Writer) throws IOException { Writer Writer) throws IOException { byte[] buf = new byte[4096]; // 4 KB buffer size byte[] buf = new byte[4096]; // 4 KB buffer size while (true) { while (true) { int bytesRead = Reader.read(buf); int bytesRead = Reader.read(buf); if (bytesRead == -1) if (bytesRead == -1) break; break; Writer.write(buf, 0, bytesRead); Writer.write(buf, 0, bytesRead); }}

7  When we use a resource that is expected to be closed, we use the try-with-resources statement Resource Management in Java try( BufferedReader fileReader = new BufferedReader( BufferedReader fileReader = new BufferedReader( new FileReader("somefile.txt")); new FileReader("somefile.txt")); ) { while (true) { while (true) { String line = fileReader.readLine(); String line = fileReader.readLine(); if (line == null) break; if (line == null) break; System.out.println(line); System.out.println(line); } catch (IOException ioex) { System.err.println("Cannot read the file ".); System.err.println("Cannot read the file ".);}

Files 8 What are Files?

 A file is a resource for storing information  Located on a storage device (e.g. hard-drive)  Has name, size, extension and contents  Stores information as series of bytes  Two file types – text and binary Files 9

 The Java File class - an abstract representation of file and directory pathnames  Has exists() method that checks if the given path is poitning to a file that exists.  Has isDirectory() method that checks if the given path is pointing to a directory. File Class in Java 10 File file = new File("hello.txt"); System.out.println("We got a file: " + file); System.out.println("Does it exists? " + file.exists()); System.out.println("Is a directory? " + file.isDirectory());

Streams Streams Basic Concepts

12  Stream is the natural way to transfer data in the computer world  To read or write a file, we open a stream connected to the file and access the data through the stream What is Stream? Input stream Output stream

13  Streams are means for transferring (reading and writing) data into and from devices  Streams are ordered sequences of bytes  Provide consecutive access to its elements  Different types of streams are available to access different data sources:  File access, network access, memory streams and others  Streams are opened before using them and closed after that Streams Basics

14  Position is the current position in the stream  Buffer keeps the current position + n bytes of the stream Stream – Example F i l e s a n d F i l e s a n d46696c e64 Length = 9 Position4669 Buffer6c e64

15  Byte based streams  Subclasses of the abstract classes InputStream and OutputStream  Character based streams  Subclasses of the abstract classes Reader and Writer  The methods for reading and writing data are similar Stream Types in Java

16  The InputStream and OutputStream classes read and write 8-bit bytes.  The Writer and Reader classes read and write 16-bit Unicode characters.  Derived classes of the above 4 abstract classes add additional responsibilities using the Decorator pattern. Stream Types in Java (2) t Plain pizza Veg pizza Pepperoni pizza

17  InputStream – byte reader  read() a single byte or an array of bytes  skip() bytes  mark() and reset() position  close() the stream  OutputStream – byte writer  write() a single byte or an array of bytes  flush() the stream (in case it is buffered)  close() the stream Byte Stream Abstract Classes

18  Reader – character reader  read() a single char or into a char array  skip() chars  mark() and reset() position  close() the stream  Writer – character writer  write() a single char or from a char array  flush() the stream (in case it is buffered)  close() the stream Character Stream Abstract Classes

19  FileInputStream, FileOutputStream  BufferedInputStream, BufferedOutputStream  ByteArrayInputStream, ByteArrayOutputStream  DataInputStream, DataOutputStream  FilterInputStream, FilterOutputStream  ObjectInputStream, ObjectOutputStream  PipedInputStream, PipedOutputStream  LineNumberInputStream  PrintStream Byte Stream Concrete Classes

20  FileReader, FileWriter  BufferedReader, BufferedWriter  CharArrayReader, CharArrayWriter  InputStreamReader, OutputStreamWriter  FilterReader, FilterWriter  ObjectReader, ObjectWriter  PipedReader, PipedWriter  StringReader, StringWriter  LineNumberReader  PrintWriter Character Stream Concrete Classes

21  Example: Read each line from a file  Wrap an InputStreamReader over an InputStream.  Then, wrap a BufferedReader over the InputStreamReader. Applying the Decorator pattern BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(fileName))); BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

22  BufferedReader  Reads text from a character input stream.  Buffers characters, providing efficient reading of chars, arrays and lines.  FileInputStream  Obtains input bytes from a file in a file system.  InputStreamReader  Bridge from byte streams to character streams.  It reads and decodes them into characters using a specified charset. Applying the Decorator pattern (2)

23  What is your format: text or binary?  Do you want random access to a file?  Are you using objects or non-objects?  What are your sources and sinks of data (like sockets, files, strings…)?  Do you need to use filtering techniques like buffering or checksumming? How to choose the correct implementation?

Readers and Writers InputStream, Reader OutputStream, Writer 24

25  Readers/Writers and Input/OutputStreams are classes which facilitate the work with streams  Two types  Text readers/writers – Reader / Writer  Provide methods.read(),.write()  Binary readers/writers – InputStream / OutputStream  Provide methods for working with binary data Input/OutputStream and Reader/Writer

26  Provides a buffer for the data in order to provide more efficient way of reading/writing. Buffered Input/Output BufferedReader bfr = BufferedReader( new FileReader( "resources/character_streams/input")); String s; while ((s = bfr.readLine()) != null) { System.out.println(s);}

27  Support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values Data streams DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( new FileOutputStream("resources/data_streams/data.save")))dos.writeInt(age);dos.writeDouble(money);dos.writeUTF(name); DataInputStream dis = new DataInputStream( new BufferedInputStream( new BufferedInputStream( new FileInputStream( new FileInputStream( "resources/data_streams/data.save")))) { System.out.println("Age: " + dis.readInt()); System.out.println("Money: " + dis.readDouble()); System.out.println("Name: " + dis.readUTF());

28  Support I/O of objects. Object streams HashMap grades = new HashMap<>(); grades.put("Pesho", 5.5); grades.put("Gosho", 3.2); grades.put("Penka", 4.75); ObjectOutputStream oos = new ObjectOutputStream( new BufferedOutputStream( new BufferedOutputStream( new FileOutputStream( new FileOutputStream("resources/object_streams/object.save")))oos.writeObject(grades); ObjectInputStream ois = new ObjectInputStream( new BufferedInputStream( new BufferedInputStream( new FileInputStream( new FileInputStream("resources/object_streams/object.save"))) System.out.println("Grades: " + ois.readObject());

29  In order to save custom objects your class should implement Serializable interface Saving Custom Objects public class Person implements Serializable{ private String name; private String name; private int age; private int age;…} static class Main(String[] args) { Person pesho = new Person("Pesho", 17); Person pesho = new Person("Pesho", 17); ObjectOutputStream oos = new ObjectOutputStream( ObjectOutputStream oos = new ObjectOutputStream( new BufferedOutputStream( new BufferedOutputStream( new FileOutputStream( new FileOutputStream("resources/object_streams/object.save"))) oos.writeObject(pesho); oos.writeObject(pesho);}

30  Java supports classical exception handling  Through the try-catch-finally construct  Streams are ordered sequences of bytes  Serve as I/O mechanisms  Can be read or written to (or both)  Can have any nature – file, network, memory, device, etc.  Serialization enables custom objects to be transferred via different streams Summary

? ? ? ? ? ? ? ? ? Java Basics – Loops, Methods, Classes

32  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with JavaCC-BY-SA  "C# Basics" course by Software University under CC-BY-NC-SA licenseC# BasicsCC-BY-NC-SA License

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg