Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

java.io - streams and files

619 views

Published on

Object-oriented programming Undergraduate Course Presentations
java.io streams and files in Java
University of Vale do Itajaí
Univali
Incremental Tecnologia
English version

Published in: Education

java.io - streams and files

  1. 1. marcello.thiry@gmail.comPackage java.io: streams and files http://3.bp.blogspot.com/- Eg1r_jQcFFk/UcAVENEyKYI/AAAA AAAAADc/5fgJlvZUlp4/s1600/sr22 -file-and-filing-cabinet.jpg Supplementary material
  2. 2. marcello.thiry@gmail.com http://ideas.scup.com/pt/files/2013/06/conte%C3%BAdo.jpg 1. Basic glossary 2. Streams and files in Java (reading and writing) 3. Text files in Java (reading and writing) Contents.
  3. 3. Basic Glossary
  4. 4. marcello.thiry@gmail.com if you do not know much about charsets, code pages, encoding, ASCII, UNICODE, etc. Before we start… Take a look in this article http://www.joelonsoftware.com/articles/Unicode.html The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky It’s a bit old, but a good start
  5. 5. marcello.thiry@gmail.com Set of characters you can use Charset Repertoire ISO-8859-1 - Western Alphabet ISO-8859-5 - Cyrillic Alphabet JIS X 0208 - Japanese Alphabet ISO-8859-7 - Greek Alphabet
  6. 6. marcello.thiry@gmail.com A numerical value assigned to each character in a character set repertoire Can be represented by one or more bytes Code Point Code Position
  7. 7. marcello.thiry@gmail.com Code Point Code Position A = 41hex (ASCII) a = 61hex (ASCII) A = 00hex 41hex (UNICODE) = 33hex 34hex (UNICODE) a = 00hex 61hex (UNICODE) = 42hex F4hex (UNICODE)
  8. 8. A coded character set* *Sometimes called code page UNICODE
  9. 9. marcello.thiry@gmail.com The way algorithm the coded characters are stored into memory Character Encoding UTF-8 UTF-16 UTF-32
  10. 10. marcello.thiry@gmail.com Character Encoding http://www.w3.org/International/articles/definitions-characters/
  11. 11. marcello.thiry@gmail.com Sequence of data elements made available over time Stream
  12. 12. marcello.thiry@gmail.com Which data elements? Byte raw binary data Character Primitive data type Object Stream
  13. 13. marcello.thiry@gmail.com A continuous stream of bytes stored in a file system Stream File http://ebiznet2u.com/wp-content/uploads/2012/07/file-viewer.jpg
  14. 14. marcello.thiry@gmail.com Region of a physical memory storage used to temporarily store data while it is being moved from one place to another Data Buffer
  15. 15. marcello.thiry@gmail.com Conversion of an object to a series of bytes, which lets a program write whole objects out to streams and read them back again Object Serialization
  16. 16. Set of routines, protocols, and tools to access a software component/module without the need to know details of its implementation Application Programming* Interface API *Also used: program
  17. 17. Streams in Java
  18. 18. marcello.thiry@gmail.com Bytes Characters automatically translates to and from the local character set Data primitive data type and String values Objects What is a stream in Java? handle I/O of
  19. 19. marcello.thiry@gmail.com Optimizes input and output by reducing the number of calls to the native API And a buffered stream?
  20. 20. marcello.thiry@gmail.com Where to use? Files Network connections sockets Blob database fields System.in standard input System.out standard output … To write/read into/from
  21. 21. marcello.thiry@gmail.com https://docs.oracle.com/javase/8/docs /api/java/io/InputStream.html https://docs.oracle.com/javase/8/docs /api/java/io/OutputStream.html
  22. 22. marcello.thiry@gmail.com read() reads a single byte read(byte[] b) reads b.length bytes into an array read(byte[] b, int off, int len) reads len bytes into an array, starting from the position off skip(long n) skips discards n bytes close() closes the stream https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
  23. 23. marcello.thiry@gmail.com mark(int readlimit) marks the current position in this input stream reset() repositions this stream to the position at the time the mark method was last called https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html And, if markSupported()...
  24. 24. marcello.thiry@gmail.com write(int b) writes a single byte write(byte[] b) writes b.length bytes from the array write(byte[] b, int off, int len) writes len bytes from the array starting at offset off flush() forces any buffered output bytes to be written out
  25. 25. marcello.thiry@gmail.com Source of data
  26. 26. marcello.thiry@gmail.com Input stream for reading BYTES from a FILE Binary files UNICODE files https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html
  27. 27. marcello.thiry@gmail.com String fileName = "c:/temp/file.exe"; int byteValue; try { InputStream in = new FileInputStream(fileName); while ((byteValue = in.read()) != -1) { System.out.format("[%2X]n", byteValue); } in.close(); } catch (IOException ex) {...}
  28. 28. marcello.thiry@gmail.com String fileName = "c:/temp/file.exe"; int byteValue; try { InputStream in = new FileInputStream(fileName); while ((byteValue = in.read()) != -1) { System.out.format("[%2X]n", byteValue); } in.close(); } catch (IOException ex) {...}
  29. 29. marcello.thiry@gmail.com FileNotFoundException For constructors that use a file name as an argument If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading
  30. 30. marcello.thiry@gmail.com Try-with-resources String fileName = "c:/temp/file.exe"; byte[] bytes = new byte[500]; int read; try { try (InputStream in = new FileInputStream(fileName)) { while ((read = in.read(bytes)) != -1) { System.out.format("%d bytes read:n", read); for (int i = 0; i < read; i++) { System.out.format("[%2X]", bytes[i]); } System.out.println(); } } } catch (IOException ex) {...}
  31. 31. marcello.thiry@gmail.com Try-with-resources String fileName = "c:/temp/file.exe"; byte[] bytes = new byte[500]; int read; try { try (InputStream in = new FileInputStream(fileName)) { while ((read = in.read(bytes)) != -1) { System.out.format("%d bytes read:n", read); for (int i = 0; i < read; i++) { System.out.format("[%2X]", bytes[i]); } System.out.println(); } } } catch (IOException ex) {...}
  32. 32. marcello.thiry@gmail.com From this point forward, all our examples will use the Try-with-resources statement
  33. 33. marcello.thiry@gmail.com Destination of data sink
  34. 34. marcello.thiry@gmail.com Output stream for writing BYTES to a FILE Binary files UNICODE files https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html
  35. 35. marcello.thiry@gmail.com String fileName = "d:/downloads/mynewfile.txt"; try { try (OutputStream out = new FileOutputStream(fileName)) { byte[] bytes = new byte[]{'T', 'E', 'S', 'T', 32, 0x41}; out.write(bytes); } } catch (IOException e) {...}
  36. 36. marcello.thiry@gmail.com And if I want to write or read objects from a stream?
  37. 37. marcello.thiry@gmail.com
  38. 38. marcello.thiry@gmail.com
  39. 39. marcello.thiry@gmail.com
  40. 40. marcello.thiry@gmail.com try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.dat"))) { out.writeObject(new User("a", "a")); out.writeObject(new User("b", "b")); out.writeObject(new User("c", "c")); out.flush(); } catch (IOException e) {...} User u; try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.dat"))) { for (int i = 0; i < 3; i++) { u = (User) in.readObject(); System.out.println(u.getLogin() + ", " + u.getPassword()); } } catch (IOException | ClassNotFoundException e) {...}
  41. 41. marcello.thiry@gmail.com Explore yourself!
  42. 42. marcello.thiry@gmail.com And beyond!
  43. 43. Using text files In Java
  44. 44. marcello.thiry@gmail.com Source of data
  45. 45. marcello.thiry@gmail.com class Reader Abstract class for reading character streams read(): reads a single character read(char[]): reads characters into an array skip(long): skips N characters close(): closes the stream https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html
  46. 46. marcello.thiry@gmail.com class FileReader Reads character files Default character encoding Default byte-buffer size https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html
  47. 47. marcello.thiry@gmail.com String fileName = "temp.txt"; String line; FileReader fileReader = new FileReader(fileName);
  48. 48. marcello.thiry@gmail.com class BufferedReader Usually wraps FileReader to improve efficiency https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Buffer size may be specified Reading of characters, arrays, and lines
  49. 49. marcello.thiry@gmail.com String fileName = "temp.txt"; String line; FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } }
  50. 50. marcello.thiry@gmail.com String fileName = "temp.txt"; String line; FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } }
  51. 51. marcello.thiry@gmail.com String fileName = "temp.txt"; String line; FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } }
  52. 52. marcello.thiry@gmail.com String fileName = "temp.txt"; String line; FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } }
  53. 53. marcello.thiry@gmail.com String fileName = “temp.txt"; String line; try { FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } } catch (FileNotFoundException ex) {... } catch (IOException ex) {... }
  54. 54. marcello.thiry@gmail.com But what about the class InputStreamReader? https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html Reads bytes and decodes them into characters using a specified charset Bridge from byte streams to character streams
  55. 55. marcello.thiry@gmail.com class InputStreamReader https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html For top efficiency, consider wrapping within a BufferedReader
  56. 56. marcello.thiry@gmail.com String line; try { InputStreamReader inputReader = new InputStreamReader(System.in); try (BufferedReader bufferedReader = new BufferedReader(inputReader)) { while (!"".equals(line = bufferedReader.readLine())) { System.out.println(line); } } } catch (IOException e) {...}
  57. 57. marcello.thiry@gmail.com Now we can use FileInputStream e InputStreamReader to read a UNICODE file
  58. 58. marcello.thiry@gmail.com try { FileInputStream in = new FileInputStream("c:/temp/fileUTF16.txt"); InputStreamReader inReader = new InputStreamReader(in, "UTF-16"); try (BufferedReader buffReader = new BufferedReader(inReader)) { int character; while ((character = buffReader.read()) != -1) { System.out.print((char) character); } } } catch (IOException e) {...}
  59. 59. marcello.thiry@gmail.com Destination of data
  60. 60. marcello.thiry@gmail.com class Writer Abstract class for writing to character streams write(int): writes a single character write(char[]): writes an array of characters write(String): writes a string close(): closes the stream https://docs.oracle.com/javase/8/docs/api/java/io/Writer.html
  61. 61. marcello.thiry@gmail.com class FileWriter Writes in character files Default character encoding Default byte-buffer size https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html
  62. 62. marcello.thiry@gmail.com String fileName = “temp.txt"; FileWriter fileWriter = new FileWriter(fileName); FileWriter fileWriter = new FileWriter(fileName, false); FileWriter fileWriter = new FileWriter(fileName, true);
  63. 63. marcello.thiry@gmail.com String fileName = "c:/temp.txt"; try { try (FileWriter fileWriter = new FileWriter(fileName)) { fileWriter.write("My first line"); fileWriter.write("rn"); // new line - windows fileWriter.write("My second line"); } } catch (IOException e) {...}
  64. 64. marcello.thiry@gmail.com class BufferedWriter Usually wraps FileWriter to improve efficiency https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html Buffer size may be specified Writing characters, arrays, and lines
  65. 65. marcello.thiry@gmail.com String fileName = "c:/temp/MyFile.txt"; try { FileWriter writer = new FileWriter(fileName, true); try (BufferedWriter buffWriter = new BufferedWriter(writer)) { buffWriter.write("My first line"); buffWriter.newLine(); buffWriter.write("My second line!"); } } catch (IOException e) {...}
  66. 66. marcello.thiry@gmail.com But what about the class OutputStreamWriter? https://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html Characters written to it are encoded into bytes using a specified charset bridge from character to byte streams
  67. 67. marcello.thiry@gmail.com class OutputStreamWriter For top efficiency, consider wrapping within a BufferedWriter https://docs.oracle.com/javase/8/docs/api/java/io/OutputStreamWriter.html
  68. 68. marcello.thiry@gmail.com try { OutputStreamWriter outWriter = new OutputStreamWriter(System.out); try (BufferedWriter buffWriter = new BufferedWriter(outWriter)) { buffWriter.write("Printing a line on the console"); buffWriter.newLine(); buffWriter.write("Printing a second line...rn"); } } catch (IOException e) {}
  69. 69. marcello.thiry@gmail.com Now we can use FileOutputStream e OutputStreamWriter to write into a UNICODE file
  70. 70. marcello.thiry@gmail.com String fileName = "c:/temp/MyNewFile.txt"; try { FileOutputStream out = new FileOutputStream(fileName); OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-16"); try (BufferedWriter buffWriter = new BufferedWriter(outWriter)) { buffWriter.write("UNICODE text"); buffWriter.newLine(); buffWriter.write("Some more..."); } } catch (IOException e) {...}
  71. 71. marcello.thiry@gmail.com References.  Java™ Platform, Standard Edition 8 API Specification. https://docs.oracle.com/javase/8/docs/api/overview-summary.html.  The Java™ Tutorials. https://docs.oracle.com/javase/tutorial/.

×