Advanced Programming in Java InputOutput Mehdi Einali 1

  • Slides: 58
Download presentation
Advanced Programming in Java Input/Output Mehdi Einali 1

Advanced Programming in Java Input/Output Mehdi Einali 1

agenda Files and I/O Streams and Java I/O File. System API Serialization 2

agenda Files and I/O Streams and Java I/O File. System API Serialization 2

Files and I/O 3

Files and I/O 3

Files and Streams What is a file? A collection of bytes stored in secondary

Files and Streams What is a file? A collection of bytes stored in secondary storage Why we need files? Persistent storage How can a program use a file? Open, read/write(append), close What are the file types? Binary, Text What is a data stream? Network, file, devices, … 4

File Types Text file Building blocks: characters txt files Xml files Binary file Building

File Types Text file Building blocks: characters txt files Xml files Binary file Building blocks: bytes Exe files Zip files PDF 5

Data Hierarchy Bit Byte Character Word 6

Data Hierarchy Bit Byte Character Word 6

Java Characters A Java character has two bytes Java supports Unicode character set standard

Java Characters A Java character has two bytes Java supports Unicode character set standard ASCII Java uses UTF-16 encoding Other unicode encodings: UTF-8 UTF-16 Other non-unicode encodings Windows-1256 7

Unicode For more information: http: //www. joelonsoftware. com/articles/Unicod e. html http: //java. sun. com/developer/technical.

Unicode For more information: http: //www. joelonsoftware. com/articles/Unicod e. html http: //java. sun. com/developer/technical. Article s/Intl/Supplementary/ http: //en. wikipedia. org/wiki/Unicode 8

Java Special Characters String s = "Salam!n. I am St. A"; System. out. println(s);

Java Special Characters String s = "Salam!n. I am St. A"; System. out. println(s); s = "\ ' ""; System. out. println(s); Salam! I am S '" A 9

Streams and java i/o 10

Streams and java i/o 10

Streams Data flowing into and out of a program (I/O) is called a stream

Streams Data flowing into and out of a program (I/O) is called a stream Streams are either binary: byte-based text: character-based (unicode) The java. io library provides classes to handle a wide variety of I/O situations 11

Streams Input Stream Output Stream 12

Streams Input Stream Output Stream 12

How to use i/o import java. io. *; Open the stream Use the stream

How to use i/o import java. io. *; Open the stream Use the stream (read, write, or both) Close the stream 13

Opening a stream There is data external to your program that you want to

Opening a stream There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream 14

Java I/O Classes Character Streams are used to read and write data which is

Java I/O Classes Character Streams are used to read and write data which is in text format (characters) Stream of characters (Unicode format) Support provided by Reader and Writer classes e. g. plain text files, web pages, user keyboard input, etc Byte Streams are used to read and write data which is in binary format (1's and 0's) Stream of bytes (raw format) Support provided by Input. Stream and Output. Stream classes e. g. images, sounds, etc. 15

Important Stream Classes - File. Input. Stream Read data in binary format from files

Important Stream Classes - File. Input. Stream Read data in binary format from files File. Output. Stream Write data in binary format to files File. Reader Read text data from files File. Writer Write text data to files 16

Java I/O Classes The java. io package offers classes used to read/write data from/to

Java I/O Classes The java. io package offers classes used to read/write data from/to files To read/write data, we instantiate a subclass of one of the 4 abstract superclasses: input output byte Input. Stream Output. Stream character Reader Writer 17

Text Files A text file is a common way to organize a file as

Text Files A text file is a common way to organize a file as a sequence of lines. Each line is a sequence of characters Each OS's file system has its own way to mark the ends of lines java. io abstracts this in a consistent way Information from text files must be parsed to identify meaningful components The Scanner class helps with parsing 18

Binary Files The term binary file is used for every other type of file

Binary Files The term binary file is used for every other type of file organization Interpreting binary files requires knowledge of how the bytes are to be grouped and interpreted Text files are also binary files; but the bytes have predefined meanings (character and line data) Binary files provide highly efficient storage Java allows entire objects to be serialized as byte sequences for this purpose 19

File. Reader Example File. Reader inf = new File. Reader("filename"); int ch. Code; while(-1

File. Reader Example File. Reader inf = new File. Reader("filename"); int ch. Code; while(-1 != (ch. Code=inf. read()) ) System. out. println( "Next char: "+(char)ch. Code); inf. close(); 20

Returned int Why does Reader. read() return int, not char ? Because you may

Returned int Why does Reader. read() return int, not char ? Because you may read an eof which is -1 and you'd have no way to distinguish between eof and a valid char value otherwise 21

Other Reader Methods Reader. read() is not commonly used Some other methods are (usually)

Other Reader Methods Reader. read() is not commonly used Some other methods are (usually) better int read(char[] cbuf, int off, int len) int read(char[] cbuf) int read(Char. Buffer target) 22

File. Writer outf = new File. Writer("filename"); outf. write('A'); outf. write('n'); outf. write("Strings too!n");

File. Writer outf = new File. Writer("filename"); outf. write('A'); outf. write('n'); outf. write("Strings too!n"); outf. close(); 23

Reader & Writers File. Readers and File. Writers provide only very basic IO capabilities

Reader & Writers File. Readers and File. Writers provide only very basic IO capabilities The read and write methods are also overloaded to read and write an array of characters File. Writer has a constructor with a boolean parameter It can be used for appending the file File. Writer(String file. Name, boolean append) 24

File. Input. Stream inf = new File. Input. Stream("filename"); int b. Code; while(-1 !=

File. Input. Stream inf = new File. Input. Stream("filename"); int b. Code; while(-1 != (b. Code=inf. read()) ) System. out. println( "Next byte: "+(byte)b. Code); inf. close(); 25

Some other Input. Stream methods: int read(byte b[]) int read(byte b[], int off, int

Some other Input. Stream methods: int read(byte b[]) int read(byte b[], int off, int len) 26

File. Output. Stream outf = new File. Output. Stream("filename"); byte[] out = {52, 99,

File. Output. Stream outf = new File. Output. Stream("filename"); byte[] out = {52, 99, 13, 10}; outf. write(out); outf. close(); 27

Input. Stream/Output. Stream File. Input. Stream and File. Output. Stream provides the same basic

Input. Stream/Output. Stream File. Input. Stream and File. Output. Stream provides the same basic IO capabilities Transfer is in bytes rather than characters. There are no "lines" in these files. How to append to a file File. Output. Stream(String name, boolean append) 28

Other classes input output byte Input. Stream Output. Stream character Reader Writer input output

Other classes input output byte Input. Stream Output. Stream character Reader Writer input output byte File. Input. Stream File. Output. Stream character File. Reader File. Writer 29

buffered input output byte Buffered. Input. Stream Buffered. Output. Stream character Buffered. Reader Buffered.

buffered input output byte Buffered. Input. Stream Buffered. Output. Stream character Buffered. Reader Buffered. Writer 30

31

31

32

32

File system api 33

File system api 33

Paths and Filenames Microsoft chose to use the backslash character in path names new

Paths and Filenames Microsoft chose to use the backslash character in path names new File. Reader("c: textfilesnewfile. txt"); What is wrong with this file name? In Java the backslash character in a String literal is an escape character "c: {tab}extfiles{newline}ewfile. txt" Either type double backslashes in String literals, or use the forward slash "c: \textfiles\newfile. txt" "c: /textfiles/newfile. txt" 34

Random. Access. File This class is not a reader/writer nor a inputstream/outputstream You can

Random. Access. File This class is not a reader/writer nor a inputstream/outputstream You can use file as binary or text file Used to access desired location of file For read or write It has a file pointer The place where you read from/write into the file You can move file pointer using seek(long) method It has different methods for reading and writing 35

Random. Access. File raf = new Random. Access. File("c: /1. txt", "rw"); byte ch

Random. Access. File raf = new Random. Access. File("c: /1. txt", "rw"); byte ch = raf. read. Byte(); System. out. println("first character : " + (char)ch); ch = raf. read. Byte(); System. out. println("second character : " + (char)ch); String line = raf. read. Line(); System. out. println("Read a line: " + line); raf. seek(5); float fl = raf. read. Float(); System. out. println("Read a float from index 5: " + fl); raf. seek(26); raf. write('r'); raf. write('n'); raf. write. Double(1. 2); raf. write. Bytes("This will complete the Demo"); raf. close(); 36

File Class The java. io. File class abstracts the connection to and properties of

File Class The java. io. File class abstracts the connection to and properties of a file or folder (directory) It does not offer read/write operations File f = new File("c: /data/sample. txt"); Sample methods: f. delete(); f. length(); f. is. File(); … File d = new File("c: /"); This object represents a folder, not a file 37

File Methods boolean can. Read(); boolean can. Write(); boolean can. Execute(); boolean exists(); boolean

File Methods boolean can. Read(); boolean can. Write(); boolean can. Execute(); boolean exists(); boolean is. File() ; boolean is. Directory() ; boolean is. Absolute() ; //constructed by ” 1” or “c: /test/1” String get. Name(); String get. Path(); // “ 1” String get. Absolute. Path() ; // “c: /test/1” String get. Parent(); long length() ; //zero for folders long last. Modified() ; String[] list() ; 38

Scanner The Scanner class is not technically an I/O class It is found in

Scanner The Scanner class is not technically an I/O class It is found in java. util You can use a Scanner wrapped around any Input. Stream object to provide sophisticated token-oriented input methods new Scanner(System. in); new Scanner(new File. Input. Stream("t. txt")); scanner = new Scanner(new File("sample. txt)); scanner. next. Double() scanner. next() 39

Formatter Also found in java. util Used to format output to text files Formatter

Formatter Also found in java. util Used to format output to text files Formatter f = new Formatter("afile. txt"); Formatter g = new Formatter(a. File. Object); The format method is the most important f. format("x=%d; s=%sn", 23, "skidoo"); similar to printf in C++ The stream can be closed using… g. close(); 40

serialization 41

serialization 41

Serialization Most Objects in Java are serializable Can turn themselves into a stream of

Serialization Most Objects in Java are serializable Can turn themselves into a stream of bytes Can reconstruct themselves from a stream of bytes A serialized object includes all instance variables Unless marked as transient Members that are Object references are also serialized Serializable is an interface The serialized file is a binary file Not a text file 42

public class Student implements Serializable{ private String name; private String student. ID; private double[]

public class Student implements Serializable{ private String name; private String student. ID; private double[] grades ; private transient double average = 17. 27; public Student(String name, String student. ID, double[] grades) { this. name = name; this. student. ID = student. ID; this. grades = grades; } public double get. Average() { double sum = 0; if(grades==null) return -1; for (double grade : grades) { sum+=grade; } return sum/grades. length; } //setters and getters for name, student. ID and grades } 43

Object Serialization Object. Output. Stream output = new Object. Output. Stream( new File. Output.

Object Serialization Object. Output. Stream output = new Object. Output. Stream( new File. Output. Stream("c: /1. txt")); Student student = new Student("Ali Alavi", "88305489", new double[]{17. 2, 18. 9, 20, 13}); output. write. Object(student); output. close(); 44

Object Deserialization Object. Input. Stream stream = new Object. Input. Stream( new File. Input.

Object Deserialization Object. Input. Stream stream = new Object. Input. Stream( new File. Input. Stream("c: /1. txt")); Student student = (Student) stream. read. Object(); System. out. println(student. get. Name()) ; System. out. println(student. get. Average ()); stream. close(); 45

Java NIO 2 46

Java NIO 2 46

The First Version of Java I/O APIs java. io package The File class limitations:

The First Version of Java I/O APIs java. io package The File class limitations: more significant functionality required (e. g. copy method) defines many methods that return a Boolean value In case of an error, an exception is better than a simple false. Poor support for handling symbolic links inefficient way of handling directories and paths very limited set of file attributes 47

Java New IO (NIO) Introduced in Java 1. 4 (2002) The key features of

Java New IO (NIO) Introduced in Java 1. 4 (2002) The key features of NIO were: Channels and Selectors Buffers Charset java. nio. charset encoders, and decoders to map bytes and Unicode symbols 48

NIO. 2 Introduced in Java 1. 7 (2011) Java 7 introduces the java. nio.

NIO. 2 Introduced in Java 1. 7 (2011) Java 7 introduces the java. nio. file package New interfaces and classes Path, Paths, and Files 49

Nio 2 filesystem classes Path interface represent the location of a file or directory.

Nio 2 filesystem classes Path interface represent the location of a file or directory. Path objects do not open files or provide any file-processing capabilities. Paths class Provides static methods used to get a Path object representing a file or directory location. 50

Nio 2 filesystem classes Files class Provides static methods for common file and directory

Nio 2 filesystem classes Files class Provides static methods for common file and directory manipulations, such as copying files; creating and deleting files and directories; getting information about files and directories; reading the contents of files; getting objects that allow you to manipulate the contents of files and directories; and more Directory. Stream interface Objects of classes that implement this interface enable a program to iterate through the contents of a director 51

Path and Paths Path is an interface while Paths is a class 52

Path and Paths Path is an interface while Paths is a class 52

Path interface The to. Path() method in the java. io. File class returns the

Path interface The to. Path() method in the java. io. File class returns the Path object; this method was added in Java 7 The to. File() method in the Path interface to get a File object 53

The Files Class the java. nio. file package Provides static methods for copy, move,

The Files Class the java. nio. file package Provides static methods for copy, move, delete, … New methods for Symbolic linked files Attributes … 54

copy Path path. Source = Paths. get(str 1); Path path. Destination = Paths. get(str

copy Path path. Source = Paths. get(str 1); Path path. Destination = Paths. get(str 2); Files. copy(path. Source, path. Destination); it will not copy the files/directories contained in the source directory you need to explicitly copy them to the destination folder 55

Listening for Changes Path path = Paths. get(". . \src"); Watch. Service watch. Service

Listening for Changes Path path = Paths. get(". . \src"); Watch. Service watch. Service = null; watch. Service = path. get. File. System(). new. Watch. Service(); path. register(watch. Service, Standard. Watch. Event. Kinds. ENTRY_MODIFY); 56

Further Reading Other java I/O classes Buffered input and output Decorator pattern in java.

Further Reading Other java I/O classes Buffered input and output Decorator pattern in java. io classes java. nio Socket Programming Object serialization applications RMI 57

end 58

end 58