33
File IO in Java File IO in Java File File FileReader / FileWriter FileReader / FileWriter Scanner / PrintWriter Scanner / PrintWriter

File IO in Java

  • Upload
    masato

  • View
    39

  • Download
    0

Embed Size (px)

DESCRIPTION

File IO in Java. File FileReader / FileWriter Scanner / PrintWriter. What We Won’t Do. FileInputStream FileOutputStream These classes are for reading streams of raw data They are most often used for images Allows you to read bytes (in binary) We will focus on characters. Packages. - PowerPoint PPT Presentation

Citation preview

Page 1: File IO in Java

File IO in JavaFile IO in Java

FileFile

FileReader / FileWriterFileReader / FileWriter

Scanner / PrintWriterScanner / PrintWriter

Page 2: File IO in Java

What We Won’t DoWhat We Won’t Do

FileInputStreamFileInputStream FileOutputStreamFileOutputStream

These classes are for reading streams of These classes are for reading streams of raw dataraw data

They are most often used for imagesThey are most often used for images Allows you to read bytes (in binary)Allows you to read bytes (in binary)

We will focus on charactersWe will focus on characters

Page 3: File IO in Java

PackagesPackages

We’ll find the classes we’re using in We’ll find the classes we’re using in the io and util packages:the io and util packages: import java.io.*;import java.io.*; import java.util.*;import java.util.*;

Page 4: File IO in Java

File ClassFile Class Constructor:Constructor:

File file = new File("c:\\data\\input.txt"); File file = new File("c:\\data\\input.txt"); Use the full or relative path (from current directory)Use the full or relative path (from current directory)

Here are some useful methods:Here are some useful methods: boolean fileExists = file.exists(); boolean fileExists = file.exists(); int length = file.length(); //length in bytesint length = file.length(); //length in bytes boolean success = file.renameTo(new File("c:\\data\\boolean success = file.renameTo(new File("c:\\data\\

new.txt"));new.txt")); boolean success = file.delete(); boolean success = file.delete(); File file = new File("c:\\data"); //can also be a directoryFile file = new File("c:\\data"); //can also be a directory

boolean isDirectory = file.isDirectory(); boolean isDirectory = file.isDirectory(); File file = new File("c:\\data"); File file = new File("c:\\data");

String[ ] fileNames = file.list(); String[ ] fileNames = file.list(); File[ ] files = file.listFiles(); File[ ] files = file.listFiles();

Page 5: File IO in Java

try... catch blockstry... catch blocks

In Java there is structure known as the In Java there is structure known as the try catch block.try catch block.

Objects can Objects can throwthrow an exception when an exception when something goes wrong to notify the something goes wrong to notify the useruser Index out of bounds is oneIndex out of bounds is one

This prevents programs from an all This prevents programs from an all out crash since the code that would out crash since the code that would cause the problem is never executed cause the problem is never executed

Page 6: File IO in Java

try... catchtry... catch

Example:Example:public void mustBeOdd(int number) throws public void mustBeOdd(int number) throws

ExceptionException

{{

if( number % 2 != 0 )//not even!!!if( number % 2 != 0 )//not even!!!

throw Exception;throw Exception;

//at this point the code is only executed if even//at this point the code is only executed if even

statements…statements…

}}

Page 7: File IO in Java

try… catchtry… catch

Since the method declares the Since the method declares the keyword keyword throwsthrows anyone that uses anyone that uses the method must the method must catchcatch it in case of it in case of an erroran error

So we tell Java we’re going to So we tell Java we’re going to trytry to to do something, but if an exception is do something, but if an exception is thrown, we will thrown, we will catchcatch it and deal it and deal with the error.with the error.

Page 8: File IO in Java

try… catchtry… catch

Files can have all sorts of things go Files can have all sorts of things go wrongwrong They might be read only and you try to They might be read only and you try to

writewrite They might be in use and not allow more They might be in use and not allow more

than one person to read from themthan one person to read from them They may no longer exist (could have been They may no longer exist (could have been

delete)delete) ……

Most file I/O requires a try/catch blockMost file I/O requires a try/catch block

Page 9: File IO in Java

FileReaderFileReader Reading each character in a file one at a time with FileReader:Reading each character in a file one at a time with FileReader:

File test = new File("C:\\test.txt");File test = new File("C:\\test.txt"); trytry {{ FileReader fr = new FileReader(test);FileReader fr = new FileReader(test); int data = fr.read();int data = fr.read(); int counter = 1;int counter = 1; while(data != -1)while(data != -1) {{ System.out.println("Character #" + counter + " is " + (char)data);System.out.println("Character #" + counter + " is " + (char)data); data = fr.read();data = fr.read(); counter++;counter++; }}

fr.close();//close the filefr.close();//close the file }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 10: File IO in Java

FileReaderFileReader Reading all characters at once with FileReader:Reading all characters at once with FileReader:

File test = new File("C:\\test.txt");File test = new File("C:\\test.txt"); trytry {{ FileReader fr = new FileReader(test);FileReader fr = new FileReader(test); char[] allAtOnce = new char[(int)test.length()];char[] allAtOnce = new char[(int)test.length()]; int charsRead = fr.read(allAtOnce);int charsRead = fr.read(allAtOnce); System.out.println("This file has " + test.length() + " bytes");System.out.println("This file has " + test.length() + " bytes"); System.out.println("Here they are!");System.out.println("Here they are!"); System.out.println(allAtOnce); System.out.println(allAtOnce);

fr.close();//close the file fr.close();//close the file }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 11: File IO in Java

FileReaderFileReader

Reading all characters at once into an array Reading all characters at once into an array is OK for small filesis OK for small files

Large files may take up too much memoryLarge files may take up too much memory This will eat up the computers resourcesThis will eat up the computers resources Can affect performance too!Can affect performance too! The read method has two other versions:The read method has two other versions:

read(char[] buffer)read(char[] buffer) Fills the array as much as possible from the files Fills the array as much as possible from the files

contentscontents read(char[] buffer, int startIndex, int length)read(char[] buffer, int startIndex, int length)

Fills the array starting at the position given for the Fills the array starting at the position given for the number of characters specifiednumber of characters specified

Page 12: File IO in Java

FileReaderFileReader Reading several characters at once with FileReader:Reading several characters at once with FileReader:

File test = new File("C:\\Documents and Settings\\Cam\\Desktop\\test.txt");File test = new File("C:\\Documents and Settings\\Cam\\Desktop\\test.txt"); trytry {{ FileReader fr = new FileReader(test);FileReader fr = new FileReader(test); int amount = 25;int amount = 25; char[] severalChars = new char[amount];char[] severalChars = new char[amount]; int charsRead = fr.read(severalChars);int charsRead = fr.read(severalChars); String allChars = new String();String allChars = new String(); while( charsRead != -1 )while( charsRead != -1 ) {{ allChars += new String(severalChars);//create a string from the charsallChars += new String(severalChars);//create a string from the chars charsRead = fr.read(severalChars);charsRead = fr.read(severalChars); }} System.out.println("File says:");System.out.println("File says:"); System.out.println(allChars);System.out.println(allChars);

fr.close();//close the filefr.close();//close the file }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 13: File IO in Java

FileWriterFileWriter Writing to a file is similarWriting to a file is similar Some things to note when you open a file Some things to note when you open a file

for writing:for writing: If the file does not exist, it will be created for youIf the file does not exist, it will be created for you If the file does exist the contents are erased, the If the file does exist the contents are erased, the

content you write becomes the new filecontent you write becomes the new file To avoid losing all the old information, you must To avoid losing all the old information, you must

either read the file first and save its contents to either read the file first and save its contents to an array or use the append methodan array or use the append method

To write a new line like you expect, \n is not To write a new line like you expect, \n is not enough for a text file, you must use a carriage enough for a text file, you must use a carriage return also (\r): \r\n return also (\r): \r\n See example next slide See example next slide

Page 14: File IO in Java

FileWriterFileWriter Writing a 10x10 multiplication table to a file:Writing a 10x10 multiplication table to a file:

File test = new File("C:\\test.txt");File test = new File("C:\\test.txt"); trytry {{ FileWriter fw = new FileWriter(test);FileWriter fw = new FileWriter(test); for( int n = 1; n <= 10; n++ )for( int n = 1; n <= 10; n++ ) {{ for( int k = 1; k <= 10; k++)for( int k = 1; k <= 10; k++) fw.write(n*k + "\t");fw.write(n*k + "\t"); fw.write("\r\n");fw.write("\r\n"); }} fw.close();fw.close(); }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 15: File IO in Java

FileWriterFileWriter AppendingAppending a 10x10 multiplication table to a file: a 10x10 multiplication table to a file:

File test = new File("C:\\test.txt");File test = new File("C:\\test.txt"); trytry {{ FileReader old = new FileReader(test);FileReader old = new FileReader(test); char[] oldData = new char[(int)test.length()];char[] oldData = new char[(int)test.length()]; old.read(oldData);//save old informationold.read(oldData);//save old information old.close();old.close(); FileWriter fw = new FileWriter(test);FileWriter fw = new FileWriter(test); fw.write(oldData);//put old data back so we can append new datafw.write(oldData);//put old data back so we can append new data for( int n = 1; n <= 10; n++ )for( int n = 1; n <= 10; n++ ) {{ for( int k = 1; k <= 10; k++)for( int k = 1; k <= 10; k++) fw.write(n*k + "\t");fw.write(n*k + "\t"); fw.write("\r\n");fw.write("\r\n"); }} fw.close();fw.close(); }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 16: File IO in Java

Not Much Help…Not Much Help… The FileReader and FileWriter class do what they The FileReader and FileWriter class do what they

say (read/write) but they don’t really have any say (read/write) but they don’t really have any additional features.additional features.

For example, what if you wanted to read a word For example, what if you wanted to read a word at a time or maybe a whole line?at a time or maybe a whole line?

What if you wanted to read the data as an int What if you wanted to read the data as an int instead of a char?instead of a char?

What if you wanted to print a line of text?What if you wanted to print a line of text? …… Let’s take a look at two classes that will help usLet’s take a look at two classes that will help us

ScannerScanner PrintWriterPrintWriter

Page 17: File IO in Java

ScannerScanner

The Scanner class works the same The Scanner class works the same way as you know of it from reading way as you know of it from reading console inputconsole input

The stream is the only thing that The stream is the only thing that changeschanges

Instead of reading from the console, Instead of reading from the console, now we want the scanner to read now we want the scanner to read from a filefrom a file

Page 18: File IO in Java

Scanner ExampleScanner Example This example reads each “word” (string separated by white space) from a This example reads each “word” (string separated by white space) from a

file and prints them one line at a time:file and prints them one line at a time: File test = new File("C:\\test.txt");File test = new File("C:\\test.txt");

trytry {{ FileReader read = new FileReader(test);FileReader read = new FileReader(test); Scanner in = new Scanner( read );Scanner in = new Scanner( read ); while( in.hasNext() )//is there something to read?while( in.hasNext() )//is there something to read? System.out.println(in.next());//next method gets a wordSystem.out.println(in.next());//next method gets a word read.close();read.close(); }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 19: File IO in Java

Scanner MethodsScanner Methods The Scanner class is LOADED with methods The Scanner class is LOADED with methods

for reading a stream:for reading a stream: hasNextInt(): next value is an inthasNextInt(): next value is an int hasNext(): next value is a stringhasNext(): next value is a string hashNextLine(): there is another line of text to hashNextLine(): there is another line of text to

readread There are many to check what’s left in the fileThere are many to check what’s left in the file next(): reads a token (separated by white space)next(): reads a token (separated by white space) nextLine(): reads a line of textnextLine(): reads a line of text nextInt(): reads the next token as an intnextInt(): reads the next token as an int …… All of the next____() methods we’ve used to get All of the next____() methods we’ve used to get

data from the console can be used on a filedata from the console can be used on a file

Page 20: File IO in Java

PrintWriterPrintWriter

The PrintWriter class behaves more The PrintWriter class behaves more like System.outlike System.out

You can print just about any data type You can print just about any data type or object with a toString method into a or object with a toString method into a filefile

You can also use the println method You can also use the println method rather than having to use \r\nrather than having to use \r\n

The advantage is you can work with The advantage is you can work with more than just chars and not have to more than just chars and not have to worry about casting/conversionsworry about casting/conversions

Page 21: File IO in Java

Person ClassPerson Class

public class Personpublic class Person{{

public Person( String name, int age )public Person( String name, int age )public String toString()public String toString(){{

return name + “\t” + age;return name + “\t” + age;}}

}}

Page 22: File IO in Java

PrintWriter ExamplePrintWriter Example This example prints an array of objects to a file:This example prints an array of objects to a file:

File test = new File("C:\\Documents and Settings\\Cam\\Desktop\\File test = new File("C:\\Documents and Settings\\Cam\\Desktop\\test.txt");test.txt");

trytry {{ FileWriter fw = new FileWriter(test);FileWriter fw = new FileWriter(test); PrintWriter writer = new PrintWriter( fw );PrintWriter writer = new PrintWriter( fw ); Person[ ] pArr = {new Person("John", 10), new Person("Bob", 12),Person[ ] pArr = {new Person("John", 10), new Person("Bob", 12), new Person("Sue", 11), new Person("Anne", 13) };new Person("Sue", 11), new Person("Anne", 13) }; for( int n = 0; n < pArr.length; n++ )for( int n = 0; n < pArr.length; n++ ) writer.println(pArr[n]);//Uses Person's toString method to printwriter.println(pArr[n]);//Uses Person's toString method to print fw.close();fw.close(); }} catch(IOException e)catch(IOException e) {{ System.out.println(e);System.out.println(e); }}

Page 23: File IO in Java

Exercises - FileUtilityExercises - FileUtility The first class we’ll create will be called FileUtilityThe first class we’ll create will be called FileUtility The class takes a path to a file in its constructor The class takes a path to a file in its constructor

and performs the following tasks (methods):and performs the following tasks (methods): public int wordCount()public int wordCount()

Returns the number of words in the fileReturns the number of words in the file public int lineCount()public int lineCount()

Returns the number of lines in the fileReturns the number of lines in the file public int count(String word)public int count(String word)

Returns the number of instances of word in the fileReturns the number of instances of word in the file public void replace(String target, String replacement)public void replace(String target, String replacement)

Should work for all instances, not just whole wordsShould work for all instances, not just whole words Ex. replace( “ing”, “abc” ) turns “flying” to “flyabc” in the Ex. replace( “ing”, “abc” ) turns “flying” to “flyabc” in the

filefile public void append( String data )public void append( String data )

Appends data to the end of the fileAppends data to the end of the file

Page 24: File IO in Java

Exercises - FileUtilityExercises - FileUtility The last 4 methods are for encryption and The last 4 methods are for encryption and

decryption, I suggest you use chars (8 bits decryption, I suggest you use chars (8 bits = 256 values) for these when you = 256 values) for these when you read/writeread/write

Cipher Encryption works like this:Cipher Encryption works like this: Take a numeric key and add that to each value Take a numeric key and add that to each value

in the alphabetin the alphabet For example a key of 2 makes aFor example a key of 2 makes ac, bc, bd, etc.d, etc.

The word “hello” with key 2 becomes: “jgnnq”The word “hello” with key 2 becomes: “jgnnq” What happens to “z”?What happens to “z”?

Wraps around back to a, then b (z Wraps around back to a, then b (z b) b) Use mod to get this effect on integersUse mod to get this effect on integers

Create the method:Create the method: public void cipherEncrypt( int key )public void cipherEncrypt( int key )

Page 25: File IO in Java

Exercises - FileUtilityExercises - FileUtility Cipher Decryption works like this:Cipher Decryption works like this:

Take a numeric key and subtract value from Take a numeric key and subtract value from each in the alphabeteach in the alphabet

For example a key of 2 makes aFor example a key of 2 makes ay, by, bz, etc.z, etc. The word “eqorwvgt” with key 2 becomes: The word “eqorwvgt” with key 2 becomes:

“computer”“computer” Create the method:Create the method:

public void cipherDecrypt( int key )public void cipherDecrypt( int key ) You can test your code by callingYou can test your code by calling

cipherEncrypt( key )cipherEncrypt( key ) cipherDecrypt( key )cipherDecrypt( key ) The result is the file is restored if done The result is the file is restored if done

correctlycorrectly

Page 26: File IO in Java

Exercises - FileUtilityExercises - FileUtility Password Encryption is a little different:Password Encryption is a little different:

Take in a password and use it to fill the beginning of an Take in a password and use it to fill the beginning of an array which contains the alphabetarray which contains the alphabet

Fill the array with values which have not been used yetFill the array with values which have not been used yet Suppose the password was “Secret”Suppose the password was “Secret” The alphabet:The alphabet:

{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z} becomes:becomes:

{s,e,c,r,t,a,b,d,f,g,h,i,j,k,l,m,n,o,p,q,u,v,w,x,y,z}{s,e,c,r,t,a,b,d,f,g,h,i,j,k,l,m,n,o,p,q,u,v,w,x,y,z}So the letter ‘a’ is now an ‘s’,So the letter ‘a’ is now an ‘s’,The letter ‘b’ is now an ‘e’, … The letter ‘b’ is now an ‘e’, … The word “testing” becomes “qtpqfkb”The word “testing” becomes “qtpqfkb”Create the methods Create the methods

public void passwordEncrypt( String word )public void passwordEncrypt( String word )public void passwordDecrypt( String word )public void passwordDecrypt( String word )

*Your alphabet consists of all 256 chars, not just 26*Your alphabet consists of all 256 chars, not just 26

Page 27: File IO in Java

Exercise – CSV filesExercise – CSV files CSV or comma separated values is a CSV or comma separated values is a

common/simple file type for displaying common/simple file type for displaying data in a table.data in a table.

Columns are separated by commas and Columns are separated by commas and rows by new linesrows by new lines

Testing,1,2,3Testing,1,2,3

Testing,A,B,CTesting,A,B,CTestingTesting 11 22 33

TestingTesting AA BB CC

Page 28: File IO in Java

Exercise – CSV filesExercise – CSV files

Make a class that takes the path to a csv Make a class that takes the path to a csv file in its constructor and loads the table of file in its constructor and loads the table of data into a 2D array (or ArrayList). data into a 2D array (or ArrayList).

Add the following methods to the class:Add the following methods to the class: public int rows()public int rows()

Returns the number of rows in the CSV fileReturns the number of rows in the CSV file public int columns()public int columns()

Returns the number of columns in the CSV fileReturns the number of columns in the CSV file public String getRow( String key )public String getRow( String key )

Searches the data and if Searches the data and if keykey is found, returns the is found, returns the row of data where it was discoveredrow of data where it was discovered

Page 29: File IO in Java

Exercise – CSV filesExercise – CSV files HTML tables have the following syntax:HTML tables have the following syntax: <table><table>

<tr><td></td><td></td></tr><tr><td></td><td></td></tr> ……</table></table>Where tr marks the start of a row and td the start of a columnWhere tr marks the start of a row and td the start of a column

In the example:In the example: Testing,1,2,3Testing,1,2,3 Testing,A,B,CTesting,A,B,C

The html would be:The html would be:<table><table>

<tr><td>Testing</td><td>1</td><td>2</td><td>3</<tr><td>Testing</td><td>1</td><td>2</td><td>3</td></tr>td></tr><tr><td>Testing</td><td>A</td><td>B</td><td>C</<tr><td>Testing</td><td>A</td><td>B</td><td>C</td></tr>td></tr>

</table></table>

Page 30: File IO in Java

Exercise – CSV filesExercise – CSV files

A google search can turn up more info on A google search can turn up more info on tablestables

The tags table, tr, and td also have options for The tags table, tr, and td also have options for line thickness/color, font, background color line thickness/color, font, background color etc.etc.

Create the method:Create the method: public void exportTo(String path, *options*)public void exportTo(String path, *options*)

Which creates a new .html file and exports the Which creates a new .html file and exports the table there. The user must have at least 4 table there. The user must have at least 4 options included when they exportoptions included when they export This could be the colors, font, lines etc.This could be the colors, font, lines etc.

Page 31: File IO in Java

Exercises - GraphicsExercises - Graphics Create a basic drawing application that allows the Create a basic drawing application that allows the

user to draw the following JGraphics shapes:user to draw the following JGraphics shapes: JRectangleJRectangle JOvalJOval JLineJLine

All shapes are made in two steps:All shapes are made in two steps: User clicks a “button” on the graph to select a shapeUser clicks a “button” on the graph to select a shape This shape will be used until the click a different buttonThis shape will be used until the click a different button The next place they click marks the starting point of the The next place they click marks the starting point of the

shapeshape The second click marks the end of the shapeThe second click marks the end of the shape

For a JRectangle or JOval this is the top left and bottom For a JRectangle or JOval this is the top left and bottom right cornerright corner

For the JLine its simple the start and end For the JLine its simple the start and end

Page 32: File IO in Java

Exercises - GraphicsExercises - Graphics

There will be a fourth button called There will be a fourth button called “save” which when the user clicks on “save” which when the user clicks on it asks them to enter a name to save it asks them to enter a name to save their graphics as (in the console their graphics as (in the console window – use a Scanner)window – use a Scanner)

The program then saves all of the The program then saves all of the shapes in this file so that it can be shapes in this file so that it can be reloaded at another timereloaded at another time

Page 33: File IO in Java

Exercises - GraphicsExercises - Graphics Create the last button called “Load” which Create the last button called “Load” which

asks the person for the name of the file to asks the person for the name of the file to load and reads it from disk and displays it on load and reads it from disk and displays it on the screenthe screen

You will have to think about a format but one You will have to think about a format but one possible way to save the shapes would look possible way to save the shapes would look like this using one shape per line of your file:like this using one shape per line of your file: Circle,3,2,5Circle,3,2,5

create new JCircle( new JPoint(3,2), 5 );create new JCircle( new JPoint(3,2), 5 ); Line,2,3,4,5 Line,2,3,4,5

creates a new JLine(2,3,4,5);creates a new JLine(2,3,4,5); Rectangle,1,2,3,4Rectangle,1,2,3,4

creates a new JRectangle( new JPoint( 1,2 ), 3,4 );creates a new JRectangle( new JPoint( 1,2 ), 3,4 );