Presentation is loading. Please wait.

Presentation is loading. Please wait.

Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks.

Similar presentations


Presentation on theme: "Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks."— Presentation transcript:

1 Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks in the context of file I/O.) Continue File Input/Output (concentrate on text I/O) Next topic - Encapsulation Winter 2015CMPE212 - Prof. McLeod1

2 Back to File I/O I will not discuss streams, which are at the root of I/O. Java provides other classes to handle these streams and make their use easier. There are many ways to do file I/O. Sometimes experimentation is needed to find the most efficient technique. I will focus on techniques that are applicable to relatively small files. BTW, file I/O is slowwwwww.... Winter 2015CMPE212 - Prof. McLeod2

3 Aside - Buffered vs Non-Buffered I/O You can choose between: Non-Buffered: you interact directly with the device – your hard-disk for example. Every read and write takes place immediately. Slowest. Winter 2015CMPE212 - Prof. McLeod3

4 Buffered vs Non-Buffered I/O, Cont. Buffered: Reads and writes take place through a memory store in RAM – a buffer. For reading – re-reads are much faster. For writing – the buffer is emptied either when it is full or when you “flush” it. Winter 2015CMPE212 - Prof. McLeod4

5 Buffered vs Non-Buffered I/O Buffered I/O is much faster as it minimizes the physical file reads and writes. But, suppose you lose your physical connection to your file before the buffer is emptied? Data can be lost and/or corrupted. Winter 2015CMPE212 - Prof. McLeod5

6 Java 7 Path Object File I/O resources and methods work with Path objects, not directly with files. The new Java 7 file I/O objects are in the java.nio library. Path import is import java.nio.file.Path; for example. (You can also let Eclipse help you find imports...) Winter 2015CMPE212 - Prof. McLeod6

7 Java 7 Path Object, Cont. To create a Path object linked to a file invoke the static Paths.get() method: Path aFile = Paths.get(filename); filename is a String. filename can contain a path like: “C:\\Users\\Alan\\workspace\\projectDemo\\src\\Stuff.txt” If there is no path then Eclipse will assume the file is in the project folder – not the src folder. Winter 2015CMPE212 - Prof. McLeod7

8 Java 7 Path Object, Cont. Folder delimiters depend on your OS. Path objects can be created from files and folders that don’t exist! Path objects can be split up, compared and joined. Path objects are also supplied to static methods in the Files class. Winter 2015CMPE212 - Prof. McLeod8

9 The Files Class Main entry point to file operations. Contains static methods that: –Create objects for file input and output. –Are used for checking, deleting, copying, creating and watching files and directories. –Can view and change file metadata. Just about all operations will require, at a minimum, a Path object. Winter 2015CMPE212 - Prof. McLeod9

10 The Files Class, Cont. The Path object created may refer to a path or file that does not exist, so you had better check before you attempt to use it. For example: if (Files.exists(file, LinkOption.NOFOLLOW_LINKS) && Files.isReadable(file) ) {... The LinkOption thing tells the method what to do if the file is a symbolic link. Winter 2015CMPE212 - Prof. McLeod10

11 Text File Input, Cont. To count the lines in a text file, for example: Charset charset = Charset.forName("US-ASCII"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) { do { line = reader.readLine(); lineCount++; } while (line != null); lineCount--; } catch (IOException err) { System.err.println("Unable to read file: " + filename); } Winter 2015CMPE212 - Prof. McLeod11

12 Easier Text File Input The Files class has a static method called.readAllLines() that reads and returns all lines of text as a List object, which can be cast to be of type ArrayList. See TextFileIOUtils.java The try with resources block is not always used even for new Java 7 code. Note use of static object generator methods. Winter 2015CMPE212 - Prof. McLeod12

13 Text File Output Again, consider buffered output only. As with input, you can create a BufferedWriter resource using Files.newBufferedWriter(). Then invoke the write() method to write a single String to the file. See the code snippet on the next slide from TextFileIOUtils.java: Winter 2015CMPE212 - Prof. McLeod13

14 Text File Output, Cont. try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) { for (int i = 0; i < text.length; i++) { writer.write(text[i] + "\r\n"); lineCount++; } } catch (IOException err) { System.err.format("IOException: %s%n", err); System.err.println("Unable to write file: " + filename); return lineCount; } Winter 2015CMPE212 - Prof. McLeod14

15 Text File Output, Cont. The.newBufferedWriter() method can also accept a third OpenOptions parameter. A few, common parameters (enums) are: –WRITE – Opens the file for write access. –APPEND – Appends the new data to the end of the file. This option is used with the WRITE or CREATE options. –TRUNCATE_EXISTING – Truncates the file to zero bytes. This option is used with the WRITE option. –CREATE_NEW – Creates a new file and throws an exception if the file already exists. –CREATE – Opens the file if it exists or creates a new file if it does not. –DELETE_ON_CLOSE – Deletes the file when the stream is closed. This option is useful for temporary files. Winter 2015CMPE212 - Prof. McLeod15

16 Text File Output, Cont. If you don’t supply a third parameter, the method will: –create a new file if it doesn’t exist, or –empty (truncate) an existing file – without warning. So, you might wish to check to see if the file exists and ask the user if he wishes to overwrite it. Winter 2015CMPE212 - Prof. McLeod16

17 Easier Text File Output The Files class also has a write() method that can write an entire ArrayList object, appending the system’s current line termination sequence to each String. This method must get an “iterable” object – it cannot work directly with a String[] object. Winter 2015CMPE212 - Prof. McLeod17

18 Text File I/O Comparisons Using TextFileIOUtils.java: Reading is a bit slower than writing. The new Java 7 reading is a bit faster than the Java 6 version. Java 7 vs Java 6 writing times are about the same – but buffering from the reading may affect these times. The effect of buffering can easily be demonstrated. The Java 7 code can be more compact and should be safer. Winter 2015CMPE212 - Prof. McLeod18


Download ppt "Today Assignment 2 is posted. Due the first Friday after Reading Week. (“Virtual” lecture looked at the use of try/catch and try with resources blocks."

Similar presentations


Ads by Google