Presentation is loading. Please wait.

Presentation is loading. Please wait.

ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.

Similar presentations


Presentation on theme: "ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name."— Presentation transcript:

1

2 ICS3U_FileIO.ppt File Input/Output (I/O)‏

3 ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name is "billy.txt”

4 ICS3U_FileIO.ppt File myFile = new File("billy.txt"); The data type of myFile is… … File What kind of data type is this? An abstract data type. (vs. concrete)‏

5 ICS3U_FileIO.ppt Create a New File createNewFile() method myFile.createNewFile(); // this creates // the file

6 ICS3U_FileIO.ppt When file creation goes horribly, horribly wrong If the file can’t be created an exception is thrown. IOException - means there was an I/O failure. It’s an unchecked exception Compiler: write some special code to handle the exception.

7 ICS3U_FileIO.ppt Exception Handlers try…catch block try { myFile.createNewFile(); System.out.println("file created"); } catch (java.io.IOException e) {//can call ‘e’ //anything System.out.println(”Oops!"); }

8 ICS3U_FileIO.ppt try…catch block try block: contains code you’re trying to execute and that might throw the exception. catch block: contains code that is executed when the exception is caught.

9 ICS3U_FileIO.ppt You Try Declare a file object Create the file Where do you suppose your program created the file? Use WinXp’s search function if you can’t locate the file yourself.

10 ICS3U_FileIO.ppt throws – the keyword Guess what? You don't absolutely need a try...catch block. You can use the throws keyword instead. It's simpler. But less elegant.

11 ICS3U_FileIO.ppt Using throw public static void main(String[] args) throws e.g. public static void main (String[] args) throws IOException, FileNotFoundException It’s simpler than try…catch but… Your program will crash when the exception occurs rather than do something elegant specified by the catch block.

12 ICS3U_FileIO.ppt Deleting Files We use the delete() method. E.g. myFile.delete(); The delete() method returns true if successful and false if not. Since we’re interacting with the OS, we should check for success. if(myFile.delete()) //OK. File was deleted. Continue processing. else System.out.println(“ERROR: File deletion failed.”);

13 ICS3U_FileIO.ppt Reading from a file We need a way to connect our program to the file we want to read. We use a stream.

14 ICS3U_FileIO.ppt Reading From A File: Creating a stream We need two things for a (useful) stream: a FileReader object and a BufferedReader object

15 ICS3U_FileIO.ppt Reading From A File: Creating a stream Create a FileReader object to use: FileReader myFileRdr = new FileReader(“billy.txt”); This presumes that “ billy.txt ” already exists. If not? An exception! FileNotFoundException (see slide 10)

16 ICS3U_FileIO.ppt Reading From A File: BufferedReader FileReader is good creating a stream to connect to a file but not much else. BufferedReader is good at reading from a stream. BufferedReader myBuffRdr = new BufferedReader (myFileRdr);

17 ICS3U_FileIO.ppt Reading From a File: BufferedReader BufferedReader needs to know what kind of streaming object it’s going to read from when it’s created. That’s why we pass the FileReader object ( myFileRdr ) to it when we create it. BufferedReader myBuffRdr = new BufferedReader (myFileRdr);

18 ICS3U_FileIO.ppt Reading from a File FileReader myFileRdr = new FileReader(“billy.txt); BufferedReader myBuffRdr = new BufferedReader(myFileRdr); myBuffRdr reads from the myFileRdr stream which is connected to billy.txt.

19 ICS3U_FileIO.ppt Using BufferedReader BufferedReader implements our old friend… … readLine() myBuffRdr.readLine() reads a line of text from the file that was pointed to by the FileReader object. i.e. we read a line from billy.txt

20 ICS3U_FileIO.ppt Using BufferedReader myBuffRdr.readLine() returns a string…(as usual) String fileLine; fileLine = myBuffRdr.readLine();

21 ICS3U_FileIO.ppt Reading until the End of the File (EOF) String fileLine; while ((fileLine = myBuffRdr.readLine()) != null) System.out.println(fileLine); At the end of the file ( EOF ), readLine() returns a special value called null instead of a string. Therefore, the loop runs, reading lines from the file, until readLine() returns null. null means we’re at the end of the file and should stop reading.

22 ICS3U_FileIO.ppt You try Follow the handout instructions to write a program called cat that puts all this together. ICS3U_catExercise.doc

23 ICS3U_FileIO.ppt Parsing/Splitting the Input String into words We need to be able to split the input line into individual words. We use the String method called split() to do this.

24 ICS3U_FileIO.ppt Parsing/Splitting the Input String into words String fileLine = myBuffRdr.readLine(); String[] words; words = fileLine.split(“ *“); We have two spaces followed by an asterisk here. This gives us an array of Strings. Each element of the array is one word from the line that we read from the file.

25 ICS3U_FileIO.ppt Parsing/Splitting the Input String into words split() uses the string inside the parentheses (i.e. the argument) to figure out how to divide up the string. If words[] was “this:is:an:unusual:line” and we wrote: words = fileLine.split(“:”); Then words[] would have “this” in element 0, “is” in element 1, “an” in element 2, “unusual” in element 3, etc. The argument to split is called a delimiter.

26 ICS3U_FileIO.ppt Parsing/Splitting the Input String into words The delimiter argument is a special type of expression called a regular expression. These are very useful tools for analyzing strings. But they can also be quite complicated. We use 2 spaces and an asterisk because that is a regular expression that means at least one but possibly many spaces. So if some words are separated by more than one space we’ll still break up the input into the words its composed of.

27 ICS3U_FileIO.ppt Print one word per line while((fileLine=myBuffRdr.readLine()) != null) { //assumes “:” is the field delimeter words = fileLine.split(“:”); for (int i = 0; i<words.length; i++) System.out.println(words[i]); }

28 ICS3U_FileIO.ppt You Do I’ve modified SamuraiSong.txt from yesterday and inserted colons between each word (using regular expressions, actually. Quite simple once you understand.) Open and read in SamuraiSong_Colonised.txt as you did in the cat exercise from yesterday. Split each input line up into a string array using a colon (“:”) as the delimeter. After reading each line from the file, print the string array word by word (I.e. each element) on a separate line.

29 ICS3U_FileIO.ppt http://java.sun.com/docs/books/tutorial/essential/io/streams.html

30 ICS3U_FileIO.ppt Writing Program Output to a File Very similar to reading from a file. Declare a FileWriter object which will connect to the file we want to write to. FileWriter myFileWrtr = new FileWriter("Billy.txt"); What do you suppose "Billy.txt" refers to?

31 ICS3U_FileIO.ppt Writing to a File Yup. It's the name of the file we want to write to. If the file doesn't exist, declaring the FileWriter object will create it. If the file does already exist, declaring the FileWriter object will overwrite it. You can also “append” to a file: FileWriter myFileWrtr = new FileWriter("Billy.txt“,true);

32 ICS3U_FileIO.ppt Writing to a File - BufferedWriter You also need a BufferedWriter (just like you needed a BufferedReader). BufferedWriter myBuffWrter = new BufferedWriter(myFWrtr);

33 ICS3U_FileIO.ppt Writing to a file - write() BufferedWriter has a write() method to use for writing a string to the file. myBuffWrtr.write("Billy is a bad boy."); myBuffWrtr.write("Bobby is too.");

34 ICS3U_FileIO.ppt Writing to a file - write() There’s a problem with the two previous lines of code. They produce outpout like this: Billy is a bad boy.Bobby is too. We need to use the newLine() method. myBuffWrtr.newLine();

35 ICS3U_FileIO.ppt Writing to a file - newLine () myBuffWrtr.write("Billy is a bad boy."); myBuffWrtr.newLine(); myBuffWrtr.write("Bobby is too."); Will produce: Billy is a bad boy. Bobby is too.

36 ICS3U_FileIO.ppt Writing to a file –format() Want more control over your output? Use the format() method in the String class – See pg 64 in your text

37 ICS3U_FileIO.ppt Writing to a file - close() When we’re done with the file we should tell the operating system to close it: myBuffWrtr.close();


Download ppt "ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name."

Similar presentations


Ads by Google