Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Basic File Input Output This handout contains examples of reading and writing to files using JAVA. Reading from a file is very similar to reading from the keyboard. Files and the keyboard are essentially just sources of input. To write to a file, you use a PrintWriter object. Once the object is instantiated it is very similar to writing to the screen using println. One new concept that file i/o is going to introduce is that of error handling or exception handling. Consider the scenario where your program attempts to open the score file but that files does not exist. This would be an error condition or an exception. We are going to talk more about exception handing as the semester progresses, but these examples give you a general idea about what is going on. In code, if you try to open a file for reading or writing and that file is not found, a FileNotFoundException is thrown. This means that the method in the API that is attempting to open the file couldn’t fine the file, so it raised, or threw, an exception. This allows the programmer to decide exactly how to recover from an issue such as this. For now, we are just going to display an error message and then exit the program. However, in the future, we might ask the user to enter a new file, or some such thing. Class Player public class Player { private String name; private int score; public Player() { name = ""; score = 0; } public Player (String n, int s) { name = n; score = s; } /** * Provide an implementation for the toString method * We'll use this to write a players data to the file. * @return */ public String toString() { String s = name + " " + score; return s; } } TestWrite.java – Version 1 import java.io.*; //for File, PrintWriter, and exception public class TestWrite { public static void main (String [] args) { Player[] pArr = { new Player("Mark", 123), new Player("Bob", 333), new Player("Sam", 122) }; //Create the File Object - represents a file File f = new File ("data.txt"); //Create a PrintWriter object reference PrintWriter pw = null; try { pw = new PrintWriter(f); } catch (FileNotFoundException e) { //if file cannot be found, a FileNotFoundException will be //thrown. this allows you to hanle errors "gracefully" //We're just going to print the error message from the exception System.out.println(e.getMessage()); //Our graceful handling will just be to exit. System.exit(1); } //Use the write method to write a String out to the file for (Player x: pArr) pw.write(x.toString() + "\n"); //ALWAYS close the file pw.close(); } } TestRead.java import java.util.*; import java.io.*; public class TestRead { public static void main (String [] args) { Player[] players = new Player[3]; String tempName; int tempScore; //Create a file object for our data file File f = new File ("data.txt"); //Create a Scanner, but connect it to the file Scanner s = null; try { s = new Scanner(f); } catch(FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } //Can't read directly into a player object //need to read into temporary variables then create //a new Player object with those values for (int i = 0; i < 3; i++) { //Read the name out of the file tempName = s.next(); //Read the score out of the file tempScore = s.nextInt(); //Create a new player object and store reference in array players[i] = new Player(tempName, tempScore); } for (Player p : players) System.out.println(p.toString()); } } TestWrite2.java import java.io.*; public class TestWrite2 { public static void main (String [] args) { Player[] pArr = { new new new new Player("Mark", 123), Player("Bob", 333), Player("Sam", 122), Player("plyr1", 222)}; //Create the File Object - represents a file File f = new File ("data2.txt"); //Create a PrintWriter object reference PrintWriter pw = null; try { pw = new PrintWriter(f); } catch (FileNotFoundException e) { //if file cannot be found, a FileNotFoundException will be //thrown. this allows you to hanle errors "gracefully" //We're just going to print the error message from the exception System.out.println(e.getMessage()); //Our graceful handling will just be to exit. System.exit(1); } //On the first line, write the size of the array so that you'll know //how many are there when you go to read pw.write(Integer.toString(pArr.length) + "\n"); //Then write each object for (Player x: pArr) pw.write(x.toString() + "\n"); //ALWAYS close the file pw.close(); } } TestRead2.java import java.util.*; import java.io.*; public class TestRead2 { public static void main (String [] args) { Player[] players = null; String tempName; String tempNumRecords; int tempScore; int numRecords; //Create a file object for our data file File f = new File ("data2.txt"); //Create a Scanner, but connect it to the file Scanner s = null; try { s = new Scanner(f); } catch(FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } //Read the number of records off the 1st line from the file //and convert to an int. Will be used to allocate players array numRecords = s.nextInt(); //now we know how many players we have, so we can allocate the players //array players = new Player[numRecords]; //Can't read directly into a player object //need to read into temporary variables then create //a new Player object with those values for (int i = 0; i < numRecords; i++) { //Read the name out of the file tempName = s.next(); //Read the score out of the file tempScore = s.nextInt(); //Create a new player object and store reference in array players[i] = new Player(tempName, tempScore); } for (Player p : players) System.out.println(p.toString()); } }