12
Accessing Files in Accessing Files in Java Java Lesson 5 Lesson 5

Accessing Files in Java

  • Upload
    yakov

  • View
    34

  • Download
    0

Embed Size (px)

DESCRIPTION

Accessing Files in Java. Lesson 5. Reading Text from a File. Use FileInputStream and DataInputStream File types are “wrapped” FileInputStream in = new FileInputStream ("nameNumber.txt"); DataInputStream s = new DataInputStream (in); - PowerPoint PPT Presentation

Citation preview

Page 1: Accessing Files in Java

Accessing Files in JavaAccessing Files in Java

Lesson 5Lesson 5

Page 2: Accessing Files in Java

22

Reading Text from a FileReading Text from a File

Use FileInputStream and DataInputStreamUse FileInputStream and DataInputStream

File types are “wrapped”File types are “wrapped”FileInputStream in = new FileInputStream FileInputStream in = new FileInputStream

("nameNumber.txt"); ("nameNumber.txt");

DataInputStream s = new DataInputStream (in);DataInputStream s = new DataInputStream (in);

Command then used isCommand then used is stringVal = s.readLine() stringVal = s.readLine()

Note Source code of Note Source code of readStrings.javareadStrings.java

Page 3: Accessing Files in Java

33

Program FeaturesProgram Features

Note the specification of exception Note the specification of exception handlinghandlingpublic static void main(String args[ ]) public static void main(String args[ ])

throws IOExceptionthrows IOException

This requires a try block and a catch blockThis requires a try block and a catch blockcatch (IOException ioe) { }catch (IOException ioe) { }

Note contents of Note contents of input file input file and resulting and resulting outputoutput

Page 4: Accessing Files in Java

44

Declaring a ClassDeclaring a Class

Declared in a separate file – Declared in a separate file – nameRec.javanameRec.java

Methods declared, implemented within the class Methods declared, implemented within the class declarationdeclaration

Note use of public specifiers (some things can Note use of public specifiers (some things can also be private)also be private)

For objects of this class to be saved as binary For objects of this class to be saved as binary file records, file records, implements Serializableimplements Serializable must be declaredmust be declared

Class will be used by another program Class will be used by another program

Page 5: Accessing Files in Java

55

Declaring a ClassDeclaring a Classpublic class nameRec extends Object implements Serializable{ 

public String name;public double dNum;public int iNum;

 public void nameRec(){

name = "";dNum=0.0;iNum = 0; }

 public String getName(){ return name; }

Must specify this for saving objects of this type

to a file

Constructor

Data attributes

Page 6: Accessing Files in Java

66

Declaring a ClassDeclaring a Classpublic void setRec (String n, double d, int i){

name = n; dNum = d; iNum = i;}public void nameRec(String n, double d, int i){

setRec (n, d, i); }

 public void printRec (){

System.out.println ("Record : "+name+" "+dNum+" "+iNum);}

Another constructor

Page 7: Accessing Files in Java

77

Creating a Binary Data FileCreating a Binary Data File

ReadNameNum.javaReadNameNum.java

nameRecnameRec object instantiated object instantiated

Open the text file to be readOpen the text file to be readFileInputStreamFileInputStream wrapped in wrapped in DataInputStreamDataInputStream

Open the file for Open the file for nameRecnameRec object output object outputFileOutputStreamFileOutputStream wrapped in wrapped in ObjectOutputStreamObjectOutputStream

Page 8: Accessing Files in Java

88

Creating a Binary Data FileCreating a Binary Data File

Prime the pumpPrime the pumpCheck forCheck forend of fileend of fileProcess theProcess therecordrecordCast objectCast objectas it is writtenas it is writtenTry to read the Try to read the next recordnext record

nRec = readRecord (in);while (nRec.getName() != null){ nRec.printRec(); s.writeObject ((nameRec) nRec); nRec = readRecord(in);}

nRec = readRecord (in);while (nRec.getName() != null){ nRec.printRec(); s.writeObject ((nameRec) nRec); nRec = readRecord(in);}

Page 9: Accessing Files in Java

99

Manipulating Text to Load the ObjectManipulating Text to Load the Object

public static nameRec readRecord (DataInputStream in) throws IOException{

String name = null, iString = null, dString = null;name = in.readLine(); iString = in.readLine();dString = in.readLine() ;nameRec temp = new nameRec ();if (dString == null) return temp; // no more recordsDouble d = Double.valueOf(dString);Integer i = Integer.valueOf(iString);int ii = i.intValue();double dd = d.doubleValue();

  temp.setRec (name, dd,ii);return temp;

}

public static nameRec readRecord (DataInputStream in) throws IOException{

String name = null, iString = null, dString = null;name = in.readLine(); iString = in.readLine();dString = in.readLine() ;nameRec temp = new nameRec ();if (dString == null) return temp; // no more recordsDouble d = Double.valueOf(dString);Integer i = Integer.valueOf(iString);int ii = i.intValue();double dd = d.doubleValue();

  temp.setRec (name, dd,ii);return temp;

}

Reading the data

Change strings to Integer and Double “wrapped” objects

Call nameRec set method

Page 10: Accessing Files in Java

1010

Reading Objects from a FileReading Objects from a File

readNameRec.javareadNameRec.java

Note Note import nameRec;import nameRec; The wrapping of the FileInputStream in the The wrapping of the FileInputStream in the

ObjectInputStream fileObjectInputStream file Instantiation of the nameRec objectInstantiation of the nameRec object throw, try, and catch specificationsthrow, try, and catch specifications

Page 11: Accessing Files in Java

1111

Reading Objects from a FileReading Objects from a Filepublic class readNameRec {

public static void main (String[] args) throws IOException, ClassNotFoundException{

ObjectInputStream s = (new ObjectInputStream (new FileInputStream ("nameNum.dat")));

nameRec nRec = new nameRec();try {

while ((nRec = (nameRec)s.readObject()) != null){

nRec.printRec();}

}catch (IOException ioe) { }catch (ClassNotFoundException cnfe) { }

}}

Do the I/O in the condition

Error handling specifications

Page 12: Accessing Files in Java

1212

Results of the File ReadResults of the File Read

Line printed by the Line printed by the printRecprintRec methodmethod