7 Streams and files import java io Overview

  • Slides: 39
Download presentation
7 Streams and files import java. io. *;

7 Streams and files import java. io. *;

Overview • • • Binary data vs textual data Simple file processing - examples

Overview • • • Binary data vs textual data Simple file processing - examples The stream model Bytes and characters Buffering Byte streams Character streams Binary streams Exploring a file system with the File class Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 2

Binary data vs text • Internally, all data is stored in binary format during

Binary data vs text • Internally, all data is stored in binary format during program execution. • Text is more readable to humans than bits! Java i/o… 10011010 1001011 … tran slati on text file ”Java i/o. . . ” Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 3

Binary data vs text • … but bits are more readable to computers than

Binary data vs text • … but bits are more readable to computers than text. • No need for expensive translations. • Binary files use less space than text files. 10011010 1001011 … binary file 100110101001011. . . Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 4

input-output • The java. io package supports inputoutput. • Input-output is particularly error-prone. –

input-output • The java. io package supports inputoutput. • Input-output is particularly error-prone. – It involves interaction with the external environment. • java. io. IOException is a checked exception. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 5

Readers, writers, byte streams • Readers and writers deal with textual input and output.

Readers, writers, byte streams • Readers and writers deal with textual input and output. – Based around the char type. • Byte streams deal with binary data. – Based around the byte type. • The address-book-io project illustrates textual IO. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 6

Text output to file • Use the File. Writer class. – Open a file.

Text output to file • Use the File. Writer class. – Open a file. – Write to the file. – Close the file. • Failure at any point results in an IOException. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 7

Text output to file try { File. Writer writer = new File. Writer("name of

Text output to file try { File. Writer writer = new File. Writer("name of file"); while(there is more text to write) {. . . writer. write(next piece of text); . . . } writer. close(); } catch(IOException e) { something went wrong when accessing the file } Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 8

Text input from a file • Use the File. Reader class. • Augment with

Text input from a file • Use the File. Reader class. • Augment with Buffered. Reader for linebased input. – Open a file. – Read from the file. – Close the file. • Failure at any point results in an IOException. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 9

Text input from the keyboard • System. in maps to the keyboard. – java.

Text input from the keyboard • System. in maps to the keyboard. – java. io. Input. Stream • Often wrapped in a java. util. Scanner: – new Scanner(System. in); • Scanner supports parsing of textual input. – next. Int, next. Line, etc. • Scanner with File an alternative to Buffered. Reader with File. Reader. – new Scanner(new File(”filename”)); Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 10

Text input from a file using a File. Reader try { Buffered. Reader reader

Text input from a file using a File. Reader try { Buffered. Reader reader = new Buffered. Reader( new File. Reader("filename")); String line = reader. read. Line(); while(line != null) { do something with line = reader. read. Line(); } reader. close(); } catch(File. Not. Found. Exception e) { the specified file could not be found } catch(IOException e) { something went wrong with reading or closing } Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 11

Text input from the keyboard using a Scanner try { Scanner in = new

Text input from the keyboard using a Scanner try { Scanner in = new Scanner(System. in); while(in. has. Next. Line()) { String line = in. next. Line(); do something with line } } catch(File. Not. Found. Exception e) { the specified file could not be found } catch(IOException e) { something went wrong with reading or closing } Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 12

The stream i/o model • Isolates programming from low level environment details – Streams

The stream i/o model • Isolates programming from low level environment details – Streams add an abstract layer smoothing out the differences between various sources (or targets) for i/o operations. • Streams can connect to external files, communication sockets, internal data structures like arrays and strings, etc Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 13

Bytes and characters • Byte – 8 bit signed integer [-128, 127] • Character

Bytes and characters • Byte – 8 bit signed integer [-128, 127] • Character – Java uses Unicode 16 bit character internally in programs. • Common external character formats: – Unicode 16 bit character – ASCII 8 bit – UTF-8 variable length • “UTF 8” – LATIN_1 • “ 8859_1” – MS-DOS (Swedish) • “Cp 850” Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 14

Buffering • A large number of single byte or character i/o operations is inefficient.

Buffering • A large number of single byte or character i/o operations is inefficient. • By using buffering larger chunks of data can be treated in fewer i/o operations – thus faster performance. • Java uses buffered streams to implement buffered i/o. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 15

Wrapper classes • Many classes in java. io act as wrapper classes (the decorator

Wrapper classes • Many classes in java. io act as wrapper classes (the decorator design pattern). • Ex. Print. Writer Buffered. Writer A Print. Writer wraps a Buffered. Writer. . . File. Writer . . . which wraps a File. Writer Print. Writer out = new Print. Writer( new Buffered. Writer( new File. Writer(”output file name”))); Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 16

Byte input stream data flow source primary byte streams secondary byte streams Input. Stream

Byte input stream data flow source primary byte streams secondary byte streams Input. Stream Buffered. Input. Stream File. Input. Stream Data. Input. Stream Pushback. Input. Stream program Byte. Array. Input. Stream Object. Input. Stream Piped. Output. Stream Piped. Input. Stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Sequence. Input. Stream Förel. 7 17

Character input stream data flow source primary char streams secondary char streams Reader File.

Character input stream data flow source primary char streams secondary char streams Reader File. Reader Char. Array. Reader ”text” Buffered. Reader Line. Number. Reader program String. Reader Pushback. Reader Piped. Writer Piped. Reader Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 18

Bridging from byte in-streams to character in-streams primary byte input stream Input. Stream. Reader

Bridging from byte in-streams to character in-streams primary byte input stream Input. Stream. Reader secondary character input stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 19

Byte input stream class relations File. Input. Stream Byte. Array. Input. Stream Piped. Input.

Byte input stream class relations File. Input. Stream Byte. Array. Input. Stream Piped. Input. Stream <<abstract>> Input. Stream Object. Input. Stream Sequence. Input. Stream Buffered. Input. Stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Filter. Input. Stream Data. Input. Stream Pushback. Input. Stream Förel. 7 20

Character input stream class relations File. Reader Input. Stream. Reader Char. Array. Reader String.

Character input stream class relations File. Reader Input. Stream. Reader Char. Array. Reader String. Reader <<abstract>> Reader Piped. Reader Line. Number. Reader Pushback. Reader Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Buffered. Reader <<abstract>> Filter. Reader Förel. 7 21

Byte Output stream data flow secondary byte streams primary byte streams Buffered. Output. Stream

Byte Output stream data flow secondary byte streams primary byte streams Buffered. Output. Stream Data. Output. Stream program target File. Output. Stream Object. Output. Stream Byte. Array. Output. Stream Piped. Input. Stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 22

Character output stream data flow secondary char streams primary char streams target Writer Buffered.

Character output stream data flow secondary char streams primary char streams target Writer Buffered. Writer program File. Writer Char. Array. Writer Print. Writer String. Writer Piped. Writer Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 ”text” Piped. Reader Förel. 7 23

Bridging from character outstreams to byte out-streams secondary character output stream Output. Stream. Writer

Bridging from character outstreams to byte out-streams secondary character output stream Output. Stream. Writer primary byte output stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 24

Byte output stream class relations File. Output. Stream Byte. Array. Output. Stream Piped. Output.

Byte output stream class relations File. Output. Stream Byte. Array. Output. Stream Piped. Output. Stream <<abstract>> Output. Stream Object. Output. Stream Filter. Output. Stream Buffered. Output. Stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Data. Output. Stream Print. Stream Förel. 7 25

Character output stream class relations File. Writer Output. Stream. Writer Char. Array. Writer String.

Character output stream class relations File. Writer Output. Stream. Writer Char. Array. Writer String. Writer Piped. Writer <<abstract>> Writer Buffered. Writer Print. Writer <<abstract>> Filter. Writer Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 26

Byte input stream operations abstract class Input. Stream int read() int read(byte[] b, int

Byte input stream operations abstract class Input. Stream int read() int read(byte[] b, int offset, int length) long skip(long n) int available() boolean marksupported() void mark(int limit) void reset() void close() Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 27

Byte output stream operations abstract class Output. Stream void write(int b) void write(byte[] b,

Byte output stream operations abstract class Output. Stream void write(int b) void write(byte[] b, int offset, int length) void flush() void close() Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 28

Character input stream operations abstract class Reader int read() int read(char[] b, int offset,

Character input stream operations abstract class Reader int read() int read(char[] b, int offset, int length) long skip(long n) boolean ready() boolean marksupported() void mark(int limit) void reset() void close() Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 29

Character output stream operations abstract class Writer void write(int c) void write(char[] b, int

Character output stream operations abstract class Writer void write(int c) void write(char[] b, int offset, int length) void write(String str, int offset, int length) void flush() void close() Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 30

Ex. Text to binary conversion • Read a text file containing long digit strings

Ex. Text to binary conversion • Read a text file containing long digit strings and write the corresponding numbers to a binary file. Explore the text_to_binary project. Buffered. Reader text file ”-2522128769” File. Reader 00000100 100101100111010100001110001 # bytes = 4 the number in 2 -complement binary format (fake) : Big. Integer File. Output. Stream Buffered. Output. Stream Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 binary file Förel. 7 31

Ex. Text to binary (2) Buffered. Reader in = new Buffered. Reader( new File.

Ex. Text to binary (2) Buffered. Reader in = new Buffered. Reader( new File. Reader(”text infile name”)); Output. Stream out = new Buffered. Output. Stream( new File. Output. Stream(”binary outfile name”)); . . . input. Line = in. read. Line(); if ( input. Line == null ) // done Big. Integer i = new Big. Integer(input. Line); loop byte[] bytes = i. to. Byte. Array(); out. write(bytes. length); out. write(bytes, 0, bytes. length); . . . Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 32

Ex. Binary to text conversion • Read a binary file containing large numbers in

Ex. Binary to text conversion • Read a binary file containing large numbers in 2 -complement binary form and write the corresponding digits to a text file. Explore the binary_to_text project. File. Input. Stream Buffered. Input. Stream binary file 00000100 100101100111010100001110001 # bytes = 4 the number in 2 -complement binary format (fake) Print. Writer : Big. Integer ”-2522128769” File. Writer Buffered. Writer Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 text file Förel. 7 33

Ex. Binary to text (2) Buffered. Input. Stream in = new Buffered. Input. Stream(

Ex. Binary to text (2) Buffered. Input. Stream in = new Buffered. Input. Stream( new File. Input. Stream(”binary infile name”)); Print. Writer out = new Print. Writer( new Buffered. Writer( new File. Writer(”text outfile name”))); . . . int no. Of. Bytes = in. read(); byte[] buf = new byte[no. Of. Bytes]; if ( in. read(buf, 0, no. Of. Bytes) == -1 ) loop // done Big. Integer i = new Big. Integer(buf); out. println(i); . . . Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 34

The java. io. File class • Objects of class File provide systemindependent information about

The java. io. File class • Objects of class File provide systemindependent information about files and directory pathnames. • Useful for directory traversal, file creation, renaming, . . . Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 35

The java. io. File class • The class File gives a plattform independent and

The java. io. File class • The class File gives a plattform independent and abstract representation of files and maps (directories) in a hierarchical file system. • File contains (among others) the methods: – get. Name() returns the name of the file – get. Path() returns the address of this file as a string – is. Directory() determines if this file is a directory – list. Files() returns a list of the files in a directory – delete() removes this file – rename. To() changes the name of this file – exists() – can. Read() checks the existense of a file checks if a file is readable Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 36

Ex. The java. io. File class import java. io. File; public class Directory. Test

Ex. The java. io. File class import java. io. File; public class Directory. Test { public static void main(String[] args) { File the. File = new File(args[0]); if (the. File. is. Directory()) { System. out. println(”A directory!"); File[] content = the. File. list. Files(); for (int i = 0; i < content. length; i++) System. out. println(content[i]. get. Name()); } else System. out. println(”A simple file!"); } } Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 37

Ex. Recursive printout of a file tree *lecture 7 // Ex. *code *filetree File.

Ex. Recursive printout of a file tree *lecture 7 // Ex. *code *filetree File. Tree. Printer. class File. Tree. Printer. java lecture 7. ppsx import java. io. File; public class File. Tree. Printer { public static final int INDENT_STEP = 3; public static void main(String[] args) { print. File. Tree(0, new File(args[0]); } private static void print. File. Tree(int depth, File file) { print. Name(depth, file); // see next slide if ( file. is. Directory() ) Composite for ( File f : file. list. Files() ) design pattern print. File. Tree(depth + 1, f); }. . . cont. Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 38

Ex. Recursive printout of a file tree. . . private static void print. Name(int

Ex. Recursive printout of a file tree. . . private static void print. Name(int depth, File file) { print. Indent. Space(depth); print. Directory. Marking(file); System. out. println(file. get. Name()); } private static void print. Indent. Space(int depth) { for ( int i = 0; i < depth*INDENT_STEP; i++ ) System. out. print(' '); // space char } private static void print. Directory. Marking(File file) { if ( file. is. Directory() ) System. out. print('*'); } } Objektorienterade applikationer, DAT 055, DAI 2, 18/19, lp 3 Förel. 7 39