© Amir Kirsh Files and Streams in Java Written by Amir Kirsh
2 Lesson’s Objectives By the end of this lesson you will: Be able to work with Text and Binary streams and files Be familiar with the character encoding importance for text streams in Java
Agenda Reading from the standard input Files and Streams Binary files Text files and character encoding Exercise
4 Reading from the standard input try { BufferedReader in = new BufferedReader( new InputStreamReader(System.in) ); String str = ""; while (str != null) { str = in.readLine(); System.out.println(str.toUpperCase()); } } catch (IOException e) { }
5 Reading from the standard input System.in an object of type InputStream A stream of bytes (NOT chars!) InputStreamReader A bridge from byte stream to character stream, can read single chars BefferedReader adds the method “readLine”
6 Files and Streams The File class represents a file or directory Supports inquiries on the file or dir, operations like replacing its name, and opening it (if it’s a file) to get a stream of bytes for read / write Stream classes represents a stream of bytes / chars InputStream InputStreamReader BefferedReader DataInputStream – and more Streams are not related only to files, we can have a stream of bytes for network sockets, ByteArray or even for a String
7 Scanner Scanner is a helper class for getting input Scanner s = new Scanner(System.in); System.out.println("Please insert a string: "); String str = s.nextLine(); System.out.println("Please insert a number: "); int i = s.nextInt(); // may throw InputMismatchException
8 Binary Files Binary Files hold data in binary format DataInputStream / DataOutputStream -- for primitive types Serialization – using the Serializable interface and the FileInputStream / FileOutputStream readObject() and writeObject() methods -- Class exercise 1: write array of integers to binary file -- Class exercise 2: serialize Hashmap to file
9 Text Files and Character Encoding Joel On SW about character encoding: – a must read! InputStream A stream of bytes (NOT chars!) InputStreamReader A bridge from byte stream to character stream, can read single chars An important parameter is the Charset Also when constructing a String out of bytes, it’s important to provide the Charset used on the byte array -- Class exercise: write a string to a text file, as UTF-8, as UTF-16 and as ISO , as ISO and as US-ASCII
Agenda Reading from the standard input Files and Streams Binary files Text files and character encoding Exercise
11 Exercise Write a program that reads numbers from the input stream, separated by EOL (=user presses enter), stopping when something that is not a number is entered. The program will send the numbers to two different files: Text file:numbers.txt -- numbers separated by “,” Binary file:numbers.bin
12 That concludes this chapter amirk at mta ac il