230 likes | 314 Views
CS2200 Software Development. Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown 2004-07). name: Henry account number: 153498 balance: €67.32. name: John account number: 439802 balance: €13.25. Example text File.
E N D
CS2200 Software Development • Lecture 36: File Processing • A. O’Riordan, 2008 • (Includes slides by Lewis/Loftus 2205 and K. Brown 2004-07)
name: Henry account number: 153498 balance: €67.32 name: John account number: 439802 balance: €13.25 Example text File • Suppose we have a file (on secondary storage device) containing bank account information called accounts.txt: Henry 153498 67.32 John 439802 13.25 The file contains ASCII characters, and can be read/written using text editor.
I/O Streams • An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. • Input stream: • Output stream:
Types of I/O in Java • Byte Streams handle I/O of raw binary data. • Character Streams handle I/O of character data, automatically handling translation to and from the local character set. • Buffered Streams optimize input and output by reducing the number of calls to the native API. • Scanning and Formatting allows a program to read and write formatted text. • I/O from the Command Line describes the Standard Streams and the Console object. • Data Streams handle binary I/O of primitive data type and String values. • Object Streams handle binary I/O of objects. • Random access files permit nonsequential, or random, access to a file's contents. • New I/O - scalable I/O, fast buffered byte and character I/O, and character set conversion Covered in these notes
Example – File input with Scanner import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog(null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr,“Message", JOptionPane.PLAIN_MESSAGE); } }
import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } } Must import the Java supplied packages that define the file-handling (and general user-interface) classes
import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } } We are dealing with an external file system, and so things may go wrong – files missing, unexpected end-of-file, etc.
import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } } declares a Scanner object, which (ultimately) reads from “accounts.txt” FileReader can take a file name or a File object Alternative: use BufferedReader, see later
import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null,"The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } } nextLine( ) is a method of class Scanner which reads the next line from the file, and returns it as a String
Closing the file. If we want to read any more text, we would now have to open the file again, and start reading from the top. import java.awt.*; import javax.swing.JOptionPane; import java.io.*; import java.util.Scanner; public class AccountReader { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader("accounts.txt")); String nameStr = in.nextLine(); String idStr = in.nextLine(); String balanceStr = in.nextLine(); in.close(); JOptionPane.showMessageDialog (null, "The first Account was:" + "\n name: " + nameStr + "\n id: " + idStr + "\n balance: “ + balanceStr, “Message", JOptionPane.PLAIN_MESSAGE); } } }
Reaching the end of the file • If we don't know how many lines are in the file, we need to check for this. For example: String inputStr = null; while (in.hasNextLine()) { inputStr = in.nextLine(); JOptionPane(null, "Just read: " + inputStr, “Message”, JOptionPane.PLAIN_MESSAGE); }
BufferedReader • BufferedReader (in package java.io) is an alternative to Scanner • // Uses BufferedReader for file input. • public static void readIt(File fromFile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(fromFile)); • //... Loop as long as there are input lines. • String line = null; • while ((line = reader.readLine()) != null) { • System.out.print(line); • } • reader.close(); • } • Note: BufferedReader has method readLine(); Scanner has method nextLine()
Reading data • These procedures will only read data of type String. • If we know that the data in the file is meant to be of some other data type, we need to convert the String afterwards. • We can use the wrapper classes (Integer, Double, Boolean, Float, etc.) and their translation methods (parseInt, parseDouble, parseBoolean, parseFloat, etc.) which take a String as input, and return as output int, double, boolean, float, etc. • Warning: to do this conversion successfully, we have to be sure we know what the Strings represent. If we read in a double, and try to convert it to an int, we will get unexpected results. Make sure you know the structure of the files you are reading.
Converting Data • public class AccountReader { • public static void main(String[] args) throws IOException { • BufferedReader fileInput = new BufferedReader( • new FileReader( new File("accounts.txt"))); • String nameStr = fileInput.readLine(); • String idStr = fileInput.readLine(); • int id = Integer.parseInt(idStr); • String balanceStr = fileInput.readLine(); • double balance = Double.parseDouble(balanceStr); • fileInput.close(); • JOptionPane.showMessageDialog (null, "id = " + id + • "\nbal = " + balance, “Message", JOptionPane.PLAIN_MESSAGE); • } • }
Writing text files • import java.io.*; • import java.awt.*; • public class AccountWriter { • public static void main(String[] args) throws IOException { • PrintWriter out = new PrintWriter( • new BufferedWriter( new FileWriter("accounts2.txt"))); • out.println("David"); • out.println("342567"); • out.println("31.98"); • out.close(); • } • }
Appending to a file • The example we have just seen creates a new file, and starts writing at the first line. If the file already existed, this would • destroy the old version, and we would lose whatever was in there. • Sometimes we want to add things to the end of a file that already exists. • FileWriter allows us to do that, using a different constructor: • FileWriter(File file, boolean append) Constructs a FileWriter object given a File object • ... new FileWriter(new File("accounts3.txt"), true)) ...
Other methods of PrintWriter • println() will print any of the basic data types. • print() will print data without taking a new line. • flush() will update the output file (BufferedWriter "buffers" its output operations, and so sometimes it will appear not to have written what we asked - flush() corrects this). • Note: Using the classes we have seen, there is no way to update a file, apart from adding text to the end. There is no method for adding text to the middle, or changing an arbitrary line in the file.
File Class • java.io.File is the central class in working with files and directories. Files and directories are both represented by File objects. • public static constant: • File.separator default path separator (e.g., "/" in Unix, "\" in Windows). • Methods (sample) • exists() true if file exists • isFile() true if this is a normal file • isDirectory() true if this is a directory • getName() get name of file or directory • getPath() get path name • The setLastModified() sets the modification date/time for the file. • For example, to set the modification time of xanadu.txt to the current time: • new File("xanadu.txt").setLastModified(new Date().getTime());
Example • import java.io.*; • import java.util.*; • class FileTest { • public static void main(String[] args) { • if (args.length != 1) { • System.err.println("ERROR: must have 1 parameter"); • System.exit(1); • } • try { • File f = new File(args[0]); • System.out.println("getName() = " + f.getName()); • boolean exists = f.exists(); • System.out.println("exists() = " + exists); • if (!exists) { • System.exit(1); • } • } catch (IOException iox) { • System.err.println(iox); • } • } • }
path JFileChooser JFileChooser chooser = new JFileChooser("."); int decision = chooser.showOpenDialog(null); File infile = chooser.getSelectedFile(); if (decision == JFileChooser.APPROVE_OPTION && infile != null) { BufferedReader fileInput = new BufferedReader( new FileReader(infile)); decision = chooser.showSaveDialog(null); File outfile = chooser.getSelectedFile(); if (decision == JFileChooser.APPROVE_OPTION && outfile != null) { PrintWriter fileOutput = new PrintWriter( new BufferedWriter( new FileWriter(outfile))); //and now do the reading and writing } }
More advanced File IO (not covered) • files can store data in different formats • text files contains sequences of ascii characters • binary files store data in the same format as main memory • file handling can be by sequential or random access • a sequential-access file is a continuous stream of data: to go back, you must open again from the beginning • text files are sequential access • a random-access file allows reads and/or writes at any position in the file