cs2200 software development

23
1 CS2200 Software Development Lecture 36: File Processing A. O’Riordan, 2008 (Includes slides by Lewis/Loftus 2205 and K. Brown 2004-07)

Upload: rea

Post on 13-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS2200 Software Development

1

CS2200 Software Development

Lecture 36: File Processing

A. O’Riordan, 2008

(Includes slides by Lewis/Loftus 2205 and K. Brown 2004-07)

Page 2: CS2200 Software Development

2

Example text File

Suppose we have a file (on secondary storage device) containing bank account information called accounts.txt:

Henry15349867.32John43980213.25

The file contains ASCII characters, and can be read/written using text editor.

name: Henryaccount number: 153498balance: €67.32

name: Henryaccount number: 153498balance: €67.32

name: Johnaccount number: 439802balance: €13.25

name: Johnaccount number: 439802balance: €13.25

Page 3: CS2200 Software Development

3

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:

Page 4: CS2200 Software Development

4

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

Page 5: CS2200 Software Development

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); }}

Example – File input with Scanner

Page 6: CS2200 Software Development

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 definethe file-handling (and general user-interface) classesMust import the Java supplied packages that definethe file-handling (and general user-interface) classes

Page 7: CS2200 Software Development

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 sothings may go wrong – files missing, unexpected end-of-file,etc.

We are dealing with an external file system, and sothings may go wrong – files missing, unexpected end-of-file,etc.

Page 8: CS2200 Software Development

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

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

Page 9: CS2200 Software Development

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 Scannerwhich reads the next line from the file, andreturns it as a String

nextLine( ) is a method of class Scannerwhich reads the next line from the file, andreturns it as a String

Page 10: CS2200 Software Development

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); }}}

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.

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.

Page 11: CS2200 Software Development

11

The output

Page 12: CS2200 Software Development

12

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);}

Page 13: CS2200 Software Development

13

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()

Page 14: CS2200 Software Development

14

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.

Page 15: CS2200 Software Development

15

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); }}

Page 16: CS2200 Software Development

16

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(); }}

Page 17: CS2200 Software Development

17

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 woulddestroy 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)) ...

Page 18: CS2200 Software Development

18

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.

Page 19: CS2200 Software Development

19

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 existsisFile() true if this is a normal fileisDirectory() true if this is a directorygetName() get name of file or directorygetPath() 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());

Page 20: CS2200 Software Development

20

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); } }}

Page 21: CS2200 Software Development

21

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 }}

path

Page 22: CS2200 Software Development

22

JFileChooser

Page 23: CS2200 Software Development

23

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