Exception Handling, Reading and Writing in Files, Serialization,

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.
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.
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.
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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
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.
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.
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.
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.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
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
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.
java.io supports console and file I/O
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.
CSG2H3 Object Oriented Programming
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
Static Members and Namespaces
Interface Segregation / Dependency Inversion
Reflection SoftUni Team Technical Trainers Java OOP Advanced
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
Using Streams, Files, Serialization
Repeating Code Multiple Times
Functional Programming
Multidimensional Arrays, Sets, Dictionaries
Functional Programming
Text Processing and Regex API
Files, Directories, Exceptions
I/O Basics.
File Types, Using Streams, Manipulating Files
Multidimensional Arrays
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Java’s Hierarchy Input/Output Classes and Their Purpose
JAVA IO.
תרגול מס' 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.
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Java Technical Trainer Software University http://softuni.bg

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

Exception Handling Basics Catch and Throw Exceptions

* Handling Exceptions In Java exceptions are handled by the try-catch-finally construction catch blocks can be used multiple times to process different exception types try { // Do some work that can raise an exception } catch (SomeException ex) { // Handle the caught exception } finally { // This code will always execute } (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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

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

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

Files What are Files?

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

File Class in Java The Java File class - an abstract representation of file and directory pathnames Has exists() method that checks if the given path is pointing to a file that exists. Has isDirectory() method that checks if the given path is pointing to a directory. 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 Basic Concepts * Streams Streams Basic Concepts (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

What is Stream? 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 Input stream Output stream

Streams Basics 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

Stream – Example Position is the current position in the stream Length = 9 Position is the current position in the stream Buffer keeps the current position + n bytes of the stream F i l e s a n d 46 69 6c 65 73 20 61 6e 64 Position Buffer 46 69 6c 65 73 20 61 6e 64

Stream Types in Java Byte based streams Character 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 (2) 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. t Plain pizza Veg pizza Pepperoni pizza

Byte Stream Abstract Classes 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)

Character Stream Abstract Classes 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)

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

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

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

Applying the Decorator pattern (2) 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.

How to choose the correct implementation? 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?

Readers and Writers InputStream, Reader OutputStream, Writer

Input/OutputStream and Reader/Writer 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

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

Data streams Support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( "resources/data_streams/data.save"))) dos.writeInt(age); dos.writeDouble(money); dos.writeUTF(name); DataInputStream dis = new DataInputStream( new BufferedInputStream( 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());

Object streams Support I/O of objects. HashMap<String, Double> 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 FileOutputStream( "resources/object_streams/object.save"))); oos.writeObject(grades); ObjectInputStream ois = new ObjectInputStream( new BufferedInputStream( new FileInputStream( System.out.println("Grades: " + ois.readObject());

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

Summary Streams are ordered sequences of bytes 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

Java Streams https://softuni.bg/courses/java-basics © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with Java" book by Svetlin Nakov & Co. under CC-BY-SA license "C# Basics" course by Software University under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.