Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files & Exception Handling

Similar presentations


Presentation on theme: "Files & Exception Handling"— Presentation transcript:

1 Files & Exception Handling
CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Last modified: 11/13/2018

2 Files and programs that work with them
A file is a collection of data, that is saved on a hard drive. Files: Programs are needed to Image (.jpg, .bmp), Display : Sound(.mpeg, .wma), ImageViewer, MP3Player Create & Modify files: Video(.avi, .wmv,.mov) Paint, Word, Outlook Webpages (.html) Extract info from files: content E.g. A program that identifies the most frequent words in a book or set of books in order to determine common words in a language. Text (.txt, .csv) We will be working with plain text and text spreadsheets (.csv). Other E.g. web crawlers Files provide a solution to have persistent data: - data can be saved into files before the program exits. data can be read again from those files when needed. Persistent data is data that is not lost when exiting the program or turning off the computer.

3 Working with files outside Java
A text file contains text (as opposed to images, video, etc) Every file is uniquely identified using two attributes: The file name. The file path. You should already know: How to create a text file. How to edit a text file, to put there the text that you want. How to store a text file in the folder that you want. How to figure out the path of the folder where a file is stored. If you do not know how to do these things, talk to the instructor or the TA.

4 Specifying location of files
BAD usage: C:\\users\\alex\\1310\\Lecture 23 This path is specific to YOUR computer. Hardcoding it will cause the program to not be able to open files when run on a different machine. CORRECT: Use just the filename: e.g. data1.txt If you run the program from Netbeans, Java will look for the file in the Project folder. (Note that the source (.java) file will be in the src directory. The data files should NOT be in src. ) Use a RELATIVE path: E.g.: lecture_data\\data1.txt E.g.: ..\\..\\all_data\\data1.txt Java (ran from Netbeans) will follow the relative path starting in the Project folder.

5 How to find the location of your project
From Netbeans: Click on File->Project Properties. At the top, see where the project folder is. Or hover with the mouse over the file name in the Projects window on the left.

6 Example 1 Connect to a physical file from hard drive. input_file
import java.util.Scanner; import java.io.File; public class Enrollments { public static void printFile(String filename) { Scanner inputFile; try { /* make a connection between a file on disk and this Java program */ inputFile = new Scanner(new File(filename)); } catch (Exception e) { System.out.printf("Failed to open file %s\n", filename); return; while(inputFile.hasNextLine()) { //any more lines? String line = inputFile.nextLine();//read 1 line System.out.printf("%s\n", line); inputFile.close();//close the connection to the file public static void main(String[] args) { printFile("enrollments.csv"); Connect to a physical file from hard drive. input_file Is an object Is of type Scanner => Can do EXACTLY the same things as the Scanner object we used to read from keyboard. Close the connection

7 Example 1 try { … } catch(..){
import java.util.Scanner; import java.io.File; public class Enrollments { public static void printFile(String filename) { Scanner inputFile; try /* make a connection between a file on disk and this Java program */ inputFile = new Scanner(new File(filename)); } catch (Exception e) System.out.printf("Failed to open file %s\n", filename); return; //exit the function if could not open file while(inputFile.hasNextLine()) //any more lines? String line = inputFile.nextLine();//read 1 line System.out.printf("%s\n", line); inputFile.close();//close the connection to the file public static void main(String[] args) printFile("enrollments.csv"); try { } catch(..){ Mechanism to deal with program crashes during runtime. new Scanner here throws a checked exception Read:

8 Web read Search and read Exceptions
difference between exceptions and errors. (Hopefully get to these links:

9 Reading from a file – all components highlighted
import java.util.Scanner; import java.io.File; public class Enrollments { public static void printFile(String filename) { // must be visible outside the try{}catch => declared here Scanner inputFile; try { /* make a connection between a file on disk (with name given by filename) and this Java program. This line can produce an Exception*/ inputFile = new Scanner(new File(filename)); } catch (Exception e) { //e-object, has info about the Exception System.out.printf("Failed to open file %s\n", filename); return; //exit the function if could not open file while(inputFile.hasNextLine()) { //any more lines? String line = inputFile.nextLine();//read 1 line System.out.printf("%s\n", line); //process data inputFile.close();//close the connection to the file public static void main(String[] args) { printFile("enrollments.csv");

10 Reading a File: Summary
Connect to the file. import java.io.File Declare and initialize to null a Scanner object In try{…} catch(){} associate the Scanner object with the file you want to read from: create a File object. create a Scanner object from a File object. Take action if file could not be opened. Typically exit the method. Read data from the file. Use hasNextLine() and nextLine(). Process the data or store it in variable(s) This is task-dependent, you do whatever is needed. Close the file. Use the close() method.

11 Storing File Contents in the Program
Often we need to store the data of the entire file in the program, to do more processing. For example, to edit a spreadsheet. We can store the data from the entire file in an ArrayList of strings. A string for each line of text in the file. Why an array list and not an array? First, because we don't know from the beginning how many lines the file has. Second, because this way we can insert more lines if we want (for example, to add data to a spreadsheet). Let's write a function readFile that: Takes as input a filename. Returns an array list of all the lines of text on the file.

12 Storing File Contents in a Variable
public static ArrayList<String> readFile(String filename) { File temp = new File(filename); Scanner inputFile; try { inputFile = new Scanner(temp); } catch (Exception e) { System.out.printf("Failed to open file %s\n", filename); return null; ArrayList<String> result = new ArrayList<String>(); while(inputFile.hasNextLine()) { String line = inputFile.nextLine(); result.add(line); inputFile.close(); return result; The solution is almost identical to our printFile function. The new lines are shown in red.

13 Extra practice Write a program that prints the content of .java files for lectures 1-> 20 from the class_code folder (Lecture1.java, Lecture 2.java,… Lecture20.java). Produce all file names, (including path) Print each file. See the Extra Slides for more examples with code to: Using the readFile method Compute length of a file (number of lines in a file) Count words in a file (uses the split method from strings)

14 Spreadsheets - Spreadsheets organize data in tables, consisting of rows and columns. - The one below shows how many students are enrolled each day in each course section. - Such a spreadsheet typically includes tens of rows (dates) and hundreds of columns (courses). Text file in comma-separated values (csv) format Can be edited with Notepad, and from Java. Date, , , 7/14/2015,33,41,21 7/17/2015,41,41,20 7/24/2015,50,42,18 7/29/2015,57,41,19 8/2/2015,58,41,18 8/5/2015,67,41,19 8/7/2015,72,41,17 Human-friendly visualization of data Other separators can be used. Below an _ is the separator. Date 7/14/2015 33 41 21 7/17/2015 20 7/24/2015 50 42 18 7/29/2015 57 19 8/2/2015 58 8/5/2015 67 8/7/2015 72 17 Date_ _ _ 7/14/2015_33_41_21 7/17/2015_41_41_20 7/24/2015_50_42_18 7/29/2015_57_41_19 8/2/2015_58_41_18 8/5/2015_67_41_19 8/7/2015_72_41_17

15

16 Store 2D data in a 2D array of String & show the data
enrollments.txt file: Date,1310,4308,5360 7/14/2015,33,41,21 7/24/2015,50,42,18 8/5/2015,67,41,19 8/7/2015,72,41,17 See the Extra slides for more examples and info. public static String[][] readSpreadsheet(String fnm){ ArrayList<String> lines = readFile(fnm); int rows = lines.size(); /* Creates an array of length "rows", that stores objects of type String[]. Those objects are initialized to null.*/ String[][] result = new String[rows][]; for (int i = 0; i < lines.size(); i++){ String line = lines.get(i); String [] values = line.split(","); result[i] = values; } return result; lines (ArrayList). Each item is a String. Has content: ["Date,1310,4308,5360", "7/14/2015,33,41,21", "7/24/2015,50,42,18", "8/5/2015,67,41,19", "8/7/2015,72,41,17"] result (2D array of String). Each item is an array of String. Has content: [ ["Date","1310","4308","5360"], ["7/14/2015","33","41","21"], ["7/24/2015","50","42","18"], ["8/5/2015","67","41","19"], ["8/7/2015","72","41","17"]] Call (use) readSpreadsheet method and save the result: String[][] data = readSpreadsheet("enrollments.txt");

17 Store 2D data in a 2D array of int & show the data
enrollments.txt file: Date,1310,4308,5360 7/14/2015,33,41,21 7/24/2015,50,42,18 8/5/2015,67,41,19 8/7/2015,72,41,17 public static int[][] fileToNumbers(String fnm){ String[][] table = readSpreadsheet(fnm); int cols, rows = table.length; int[][] res = new int[rows][]; for (int r = 0; r < rows; r++){ cols = table[i].length; res[r] = new int[cols-1];//skip date for(int c=0; c<cols; c++){ String nStr = table[r][c+1]; res[r][c]= Integer.parseInt(nStr); } return res; table (2D array of String). Each item is an array of String. Has content: [ ["Date","1310","4308","5360"], ["7/14/2015","33","41","21"], ["7/24/2015","50","42","18"], ["8/5/2015","67","41","19"], ["8/7/2015","72","41","17"]] res (2D array of int). [ null, null, null] [ [1310,4308,5360], [33,41,21], [50,42,18], [67,41,19], [72,41,17] ] Call (use) fileToNumbers method and save the result: int[][] data = fileToNumbers("enrollments.txt"); Note c vs c+1 use.

18 Writing Data to a File To write to a file, we associate a file with a PrintWriter object. Then, we print to the file exactly as we print user input. We can use printf, println, and so on.

19 Writing Data to a File Question: import java.io.PrintWriter;
public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; //declare out object outside the try-catch try // the out object is the connection to the file out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); // exit the main function out.printf("writing a line to a file.\n"); \\ write to the file out.println("writing a second line."); out.close();//imp: finishes writing to the file, releases the file System.out.printf("Done writing to file %s.\n", filename); Question:

20 Issues Overwriting an existing file Notepad editor problem:
What happens if your file already contained some data, before you ran this program? The previous data is lost. Notepad editor problem: On Windows, if you open the text file created above using Notepad, it shows it all as one long line. This is a problem with Notepad. Other editors will show the file fine (with the lines as intended) See the next slide for a solution to it.

21 Different OS may have different symbols for new line: Notepad Issue with display of the output file
import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); String newLineSep = System.getProperty("line.separator"); out.printf("writing a line to a file." + System.getProperty("line.separator") ); out.printf("writing a second line." + newLineSep); out.close(); System.out.printf("Done writing to file %s.\n", filename); On Windows, if you open the text file using Notepad, it shows as one long line. This is a problem with Notepad. Other editors show the file fine. To fix this problem use: - println or System.getProperty( "line.separator") instead of \n for a newline.

22 Writing Data to a File: Recap
Connect to the file Import java.io.PrintWriter. Declare and Initialize to null a PrintWriter variable called out In try{…} associate the PrintWriter variable with a file. out = new PrintWriter(filename); In the catch clause, give the actions to be taken if the file could not be opened (invalid filename, read-only file, etc). Write whatever data you want. Use out.printf, and NOT System.out.printf (which would just print to the screen). Close the file. If you forget this step, some or all your data may not be saved in the file. The file will be created (if it didn’t exist before) and overwritten (old content erased) if it existed before. The file will be created in the Project folder.

23 Example: Convert to Squares
Write a function: saveSquares(inName,outName) that: Reads numbers from a file named inName that just contains numbers, one per line. Writes to a file named outName, the square of each number that it read from the input file. Logic: Read the lines from the input file (open and close the file). Open output file. For each line in the input: Convert string to double. Compute the square. Save the square to the output file on a new line. Close the output file. numbers.txt 7 4 5 2 -8 9 10 squares.txt 49 16 25 4 64 81 100

24 public static void saveSquares(String inputFile, String outputFile)
{ ArrayList<String> lines = readFile(input_file); PrintWriter out = null; try out = new PrintWriter(output_file); } catch (Exception e) System.out.printf("Error: failed to open %s.\n", outputFile); return; for (int i = 0; i < lines.size(); i++) double number; number = Double.parseDouble(lines.get(i)); System.out.printf("Error: %s is not a number.\n", lines.get(i)); out.printf("%.2f\r\n", number * number); out.close();

25 Other Java Classes Note that there are other ways (classes) in Java to read and write to a file.

26 Nested “Stuff” in various forms
file: quizAnswers.txt In code: nested loops, nested if statements In collections: nested arrays (2D arrays/tables) Nested ArrayList (ArrayList of ArrayLists) In file content: “nested format” E.g. consider a file that stores student answers to a quiz. On each line it has categories separated by semicolon, and within each category items separated by comma. Below the categories are: Name;Animals;Colors;Countries;Planets There can be a variable number of categories: E.g. each line in a file gives data for a table Sam;cat,dog,elephant; white,black;;Jupiter,Mars Alice;mouse,horse;red,blue,green,cyan;Peru,U.S.,U.K.;Earth ;;;; John;skunk;black;China;Mars file: tables.txt Write a method to convert a quizAnswers file into a formated one 1,2,3,4;5,6,7,8;9,0,1,2 143,23,1;5,2,90; 10;20;30;40;50;60;70;80;90;100

27 Practice Sam;cat,dog,elephant; white,black;;Jupiter,Mars Alice;mouse,horse;red,blue,green,cyan;Peru,U.S.,U.K.;Earth ;;;; John;skunk;black;China;Mars Write a method that takes a file such as quizAnswers.txt and produces another file that is formatted nicely. - The name of the new file will be given as an argument. - For formatting, reserve 15 spaces for each item. Sam Animals: cat dog elephant Colors: white black Countries: Planets: Jupiter Mars Alice Animals: mouse horse Colors: red blue green cyan Countries: Peru U.S U.K. Planets: Earth Animals: Colors: Planets: John Animals: skunk Colors: black Countries: China Planets: Mars

28 Did you know that you can create a Scanner object on a String?
Try: String s1 = " \nPeppa Pig\nwhite red blue"; String s2 = " \nPeppa Pig\nwhite red blue\n"; Scanner strScan = new Scanner(s1); // try calling next(), nextLine(), nextInt()... // read the last line with next vs nextLine from s1 and s2

29

30 Extra slides Useful examples Split method from strings explained
Use/call the readFile method in another method Compute length of a file (as number of lines in the file) Count words in a file Split method from strings explained Read and store 2D data from a file in the program in: Nested arrays Nested ArrayLists Writing to a file step by step Exception handling More detailed cover of topics in the above slides)

31 Reading from a file: Examples and code

32 Using the readFile Function
Let's rewrite function filePrint, so that it uses the readFile function that we just wrote. public static void printFile(String filename) { ArrayList<String> lines = readFile(filename); if (lines == null) return; } int length = 0; for (int i = 0; i < lines.size(); i++) String line = lines.get(i); System.out.printf("%s\n", line);

33 A Second Example: Length of a File
Let's write a function fileLength that: Takes as input a filename. Returns the number of characters in that file. Hint: use the readFile function that we already have. public static int fileLength(String filename) { ArrayList<String> lines = readRile(filename); if (lines == null) { return 0; } int length = 0; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); length += line.length(); return length;

34 A Third Example: Counting Words
Let's write a function countWords that: Takes as input a filename. Returns the number of words in that file. Question: how can we count the number of words in a string of text?

35 A Third Example: Counting Words
Let's write a function count_words that: Takes as input a filename. Returns the number of words in that file. Question: how can we count the number of words in a string of text? Words are typically separated by space. However, they could also be separated by commas, periods, and other punctuation. The String.split method can be used to split text into words. – See Extra slides at the end to learn about it.

36 A Third Example: Counting Words
public static int countWords(String filename) { ArrayList<String> lines = readFile(filename); if (lines == null) { return 0; } int counter = 0; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] words = line.split("[,.- ]"); counter += words.length; return counter; Here we specify that words are separated by commas, periods, dashes, spaces.

37 The split Method The split method separates a string into an array of "words" (smaller strings). Argument: a string specifying the characters that separate the words. public class example { public static void main(String[] args) String text = "Today is a hot summer day."; String[] words = text.split(" "); for (int i = 0; i < words.length; i++) System.out.printf("word[%d] = %s\n", i, words[i]); } Output: words[0] = Today words[1] = is words[2] = a words[3] = hot words[4] = summer words[5] = day.

38 The split Method You can specify multiple characters that separate words, as seen in this example. In the example below, we say that words are separated by comma, space, and dash. Important: to specify multiple characters, you must enclose them in square brackets: []. public class example { public static void main(String[] args) { String text = "Let's count: One,two,three."; String[] words = text.split("[, -]"); for (int i = 0; i < words.length; i++) System.out.printf("word[%d] = %s\n", i, words[i]); } Output: word[0] = Let's word[1] = count: word[2] = One word[3] = two word[4] = three.

39 The split Method You can specify multiple characters that separate words, as seen in this example. In the example below, we say that words are separated by comma, space, and dash. Important: to specify multiple characters, you must enclose them in square brackets: [] (see the example argument: "[, -]"). public class example { public static void main(String[] args) { String text = "Let's count: One,two,three."; String[] words = text.split("[, -]"); for (int i = 0; i < words.length; i++) System.out.printf("word[%d] = %s\n", i, words[i]); } Output: word[0] = Let's word[1] = count: word[2] = One word[3] = two word[4] = three.

40 Storing a Spreadsheet in a Variable
A spreadsheet is a table. You can specify a row and a column, and you get back a value. In a spreadsheet: Each value is a string (that we may possibly need to convert to a number). Each row is a sequence of values, thus can be stored an array (or ArrayList) of strings. The spreadsheet data is a sequence of rows, thus can be stored as an array (or ArrayList) of rows, thus an array (or ArrayList) of arrays (or ArrayLists) of strings.

41 Storing a Spreadsheet in a Variable
Therefore, we have a few choices on how to store spreadsheet data in a variable. Our variable can be: An array of arrays of strings. An array of ArrayLists of strings. An ArrayList of arrays of strings. An ArrayList of ArrayLists of strings.

42 Storing a Spreadsheet in a Variable
We will implement two of those options. We will write functions that read a spreadsheet and store its data as: An array of arrays of strings. An ArrayList of ArrayLists of strings.

43 Storing a Spreadsheet in a 2D Array
If we store a spreadsheet as an array of arrays of strings, the variable looks like this: String[][] data. data[i] corresponds to the i-th line of the spreadsheet. data[i] contains an array of strings. data[i][j] holds the spreadsheet value for row i, column j. Let's write a function readSpreadsheet that: Takes as input a filename. Returns an array of arrays of strings storing all the data in the spreadsheet.

44 Storing a Spreadsheet in a 2D Array
public static String[][] readSpreadsheet(String filename) { ArrayList<String> lines = readFile(filename); int rows = lines.size(); // The row below creates an array of length "rows", that stores // objects of type String[]. Those objects are initialized to null. String[][] result = new String[rows][]; for (int i = 0; i < lines.size(); i++) String line = lines.get(i); String [] values = line.split(","); result[i] = values; } return result;

45 Storing a Spreadsheet in a 2D ArrayList
If we store a spreadsheet as an array list of array lists of strings, the variable looks like this: ArrayList<ArrayList<String>> data. data.get(i) corresponds to the i-th line of the spreadsheet. data.get(i) is an ArrayList of strings. data.get(i).get(j) holds the spreadsheet value for row i, column j. Let's write a function readSpreadsheet that: Takes as input a filename. Returns an array list of ArrayLists of strings storing all the data in the spreadsheet.

46 Storing a Spreadsheet in a 2D ArrayList
public static ArrayList<ArrayList<String>> readSpreadsheet(String filename) { ArrayList<String> lines = readFile(filename); ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); for (int i = 0; i < lines.size(); i++) String line = lines.get(i); String [] values = line.split(","); ArrayList<String> values_list = new ArrayList<String>(); for (int j = 0; j < values.length; j++) values_list.add(values[j]); } result.add(values_list); return result;

47 Writing to a file step-by-step

48 Writing Data to a File import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); out.printf("writing a line to a file.\n"); out.printf("writing a second line.\n"); out.close(); System.out.printf("Done writing to file %s.\n", filename); Step 1: Make sure you import java.io.PrintWriter.

49 Writing Data to a File import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); out.printf("writing a line to a file.\n"); out.printf("writing a second line.\n"); out.close(); System.out.printf("Done writing to file %s.\n", filename); Step 2: Initialize PrintWriter object to null (so that we can associate it with a file using try … catch).

50 Writing Data to a File import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); out.printf("writing a line to a file.\n"); out.printf("writing a second line.\n"); out.close(); System.out.printf("Done writing to file %s.\n", filename); Step 3: Associate the PrintWriter object with a file. We need to use try … catch, to catch the case where for some reason the file could not be opened (invalid filename, read-only file, etc).

51 Writing Data to a File Step 4: Write whatever data you want.
import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); out.printf("writing a line to a file.\n"); out.printf("writing a second line.\n"); out.close(); System.out.printf("Done writing to file %s.\n", filename); Step 4: Write whatever data you want. Note that we use out.printf, and NOT System.out.printf (which would just print to the screen).

52 Writing Data to a File Step 5: close the file.
import java.io.PrintWriter; public class file_writing_example { public static void main(String[] args) { String filename = "out1.txt"; PrintWriter out = null; try out = new PrintWriter("out1.txt"); } catch (Exception e) System.out.printf("Error: failed to open file %s.\n", filename); System.exit(0); out.printf("writing a line to a file.\n"); out.printf("writing a second line.\n"); out.close(); System.out.printf("Done writing to file %s.\n", filename); Step 5: close the file. If you forget this step, some or all your data may not be saved in the file.

53 Exception Handling (try … catch)
Suppose that a line of code may make your program crash, by throwing an exception. You can prevent the crash, by catching the exception, using try … catch. This is called exception handling. try { line_that_may_cause_crash; } catch (Exception e) code for the case where something went wrong. Code for the case where everything went fine. variables declared inside here are not visible outside { }


Download ppt "Files & Exception Handling"

Similar presentations


Ads by Google