310 likes | 630 Views
[M]ost important , but also most elusive, aspect of any tool is its influence on the habits of those who train themselves in its use. . Edsger Dijkstra. CSC 213 – Large Scale Programming. Lecture 10: File I/o In JAva. Image To Sharpen. I have a (fuzzy) 1024 x 768 picture to sharpen
E N D
[M]ost important, but also most elusive, aspect of any tool is its influence on the habits of those who train themselves in its use. Edsger Dijkstra
CSC 213 – Large Scale Programming Lecture 10:File I/o In JAva
Image To Sharpen • I have a (fuzzy) 1024 x 768 picture to sharpen • Only 786,432 numbers to type into photo application • After analysis, must click & update each pixel
More Data Entry Positions • Testing improved jet designs for oeingB-ay • Using program to simulate designs' lift & drag • 5 possible designs (each 150MB) to test this iteration • Once results available, will tweak & retest designs • Need room of touch typists for all this data entry
This Is (Semi-Real) Problem • Large hadron collider about to come on-line • No black hole when smashing particles at high speeds • Creates 28.5 GB/minfor nerds seeking truth & beauty
This Is (Semi-Real) Problem • Large hadron collider about to come on-line • No black hole when smashing particles at high speeds • Creates 28.5 GB/minfor nerds seeking truth & beauty • Hired trained monkeys to type data into programs
This Is (Semi-Real) Problem • Large hadron collider about to come on-line • No black hole when smashing particles at high speeds • Creates 28.5 GB/minfor nerds seeking truth & beauty • Hired trained monkeys to type data into programs college students
Yeah, Right • Real world demands we use files for most I/O • Data files used to start and/or end most projects • May contain: game levels, analysis results, CCD pics • Way to read & write files needed to be useful
Reading Text File • Surprise! Already know how to do this work • In fact, this is part of Java been using for long time • Based upon Unix arcanathat is suddenly relevant • Unix (& Java) treat everything as file • Keyboards, files, network connections, mice, etc. • java.util.Scanner works with all files • Change constructor call & this will be good to go
Reading a Text File • Must first instantiate java.io.File object • Pass String filename to the File constructor • Throws a (checked) exception if file does not exist • Another IOException possible for other odd errors • Once created, use File to create Scanner • Reads file's data rather than typing into keyboard • At the same time, works like any other Scanner
Reading a Text File try {File readFile = new File("bob.dat");Scanner scan = new Scanner(readFile);while (scan.hasNext()) { String line = scan.nextLine();System.out.println(line);}scan.close(); } catch (FileNotFoundExceptionfnfe) {System.err.println("Make the file, moron!"); } catch (IOExceptionioe) {ioe.printStackTrace(); }
Typical File I/O • Ordinarily we read files sequentially Scannerscan;// Instantiate a Scannerscan for the “file” belowchar c = ‘’;while (c != ‘s’) { c = scan.nextChar();} This is an example file we access scan
Typical File I/O • Ordinarily we read files sequentially Scannerscan;// Instantiate a Scannerscan for the “file” belowchar c = ‘’;while (c != ‘s’) { c = scan.nextChar();} This is an example file we access scan
Typical File I/O • Ordinarily we read files sequentially Scannerscan;// Instantiate a Scannerscan for the “file” belowchar c = ‘’;while (c != ‘s’) { c = scan.nextChar();} This is an example file we access scan
Typical File I/O • Ordinarily we read files sequentially Scannerscan;// Instantiate a Scannerscan for the “file” belowchar c = ‘’;while (c != ‘s’) { c = scan.nextChar();} This is an example file we access scan
Typical File I/O • Ordinarily we read files sequentially Scannerscan;// Instantiate a Scannerscan for the “file” belowchar c = ‘’;while (c != ‘s’) { c = scan.nextChar();} This is an example file we access scan
Writing a Text File • Writing a text file only slightly more complicated • Console is file in Unix, so can guess where this goes • Need to first decide what should happen to file • Easy if file does not exist create file & write to it • Else what should happen to file's current contents? • Mode used at opening determines file's contents • If opening file in write mode, erases file at the start • Starts at end of file in append mode, saving the data
Opening File For Writing • Create instance of java.io.FileWriter • Must specify mode to open file at this time • Be very careful with this – there is no undo here! • If file is impossible and so cannot be written to • Cannot be done, so system throws IOException • Not told if file existed before this command FileWriterfw=new FileWriter("b.txt", false); FileWriter app=new FileWriter("bob.java",true);
Second Step To Writing Files • FileWriter helps, but slow and hard to use • Faster, simpler approach would be much nicer • Using FileWritercreate BufferedWriter • Cannot change mode; must take care initially • Two methods used to write out data to file • Both methods will expand file & advance pointer • Start writing new line – newLine() • write(String s)– writes sto file • End writing & save results with close()
Writing a Text File try {FileWriterfw = new FileWriter(“b.t”, true);BufferedWriterbw = new BufferedWriter(fw);for (inti = 10; i > 0; i--) {bw.write(“T minus ”);bw.write(i + “”);bw.newLine();}bw.write(“Blast off!”); bw.close(); }catch (IOExceptionioe) {ioe.printStackTrace(); }
RandomAccessFile • Built into Java's standard set of classes • Found in the java.io package • New or existing files can be accessed with it RandomAccessFileraf = new RandomAccessFile("f.txt","rw"); • First argument ("f.txt") is name of file used • Access to file specified ("rw") in second parameter • Using write access ("w") erases any data in the file • Read & write anywhere in file using instance
Reading RandomAccessFile • Defines methods to read most primitive types:booleanreadBoolean()intreadInt() double readDouble() • Reads & returns value read from file • Binary encoding needed for these to work • File will store 32-bit int, not "125" • Not human readable, but not really needed • Can shrink files; always makes sizes predictable
Reading RandomAccessFile • Reading Strings takes a little extra workString readUTF() • Requires that String was recorded in UTF format • Not totally readable, but makes sense to machines • Or use readChar()to read in String… • …but need null character ('\0') at end • End of String not easy to find without some hint • Also remember that Java’s char not always readable • readByte()is readable, but needs typecast
Writing RandomAccessFile • Also defines methods to write to a file: void writeInt(inti) void writeDouble(double d)void writeUTF(String s) • Writes value at location in the file we are currently at • As it is needed, methods extend file also • When writing data, erases anything there previously
RandomAccessFile I/O • Unless specified stillread &write sequentially RandomAccessFileraf = new …;char c = ‘’;while (c != ‘s’) { c = (char)raf.readByte();raf.writeByte((byte)c);} This is an example file we access
Skipping Around The File • RandomAccessFile allows moving in the file • Skip past sections using intskipBytes(int n) • void seek(long pos)moves to position in file • Positions specified as bytes from beginning of file
RandomAccessFile I/O • Sequential access is no longer required RandomAccessFileraf = new …; char c;raf.skipBytes(raf.length()-1);c = (char)raf.readByte();raf.seek(0);raf.writeByte((byte)c); This is an example file we access
RandomAccessFile I/O • Sequential access is no longer required RandomAccessFileraf = new …; char c;raf.skipBytes(raf.length()-1);c = (char)raf.readByte();raf.seek(0);raf.writeByte((byte)c); shisis an example file we access
For Next Lecture • Week #4 assignmentavailable on Angel • Continues to be due Wednesday at 5PM • Ask me questions, if you have trouble on a problem • Will be talking about indexed files on Friday • What are they and why should Steve be excited? • Why does CS department require you to learn them? • Why does it seem like they are part of project #1?