File I/O



File I/O

Reading and Writing from a File

Lupoli.txt

|* ALWAYS starts here ----------------------------------->\n (end of line or whole line) |

|----------------------------------------------------------------------------------------------------( |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

|eof – invisible marker placed on the file |

When reading IN from a file

1. YOU ARE THE ONE WHO CREATED THE FILE!!!! So you know how it is laid out.

2. Since you are reading values IN, do NOT set any variables in your program!!!

When writing OUT to a file

1. YOU ARE THE ONE WHO CREATING THE FILE!!!! So you design how it is laid out.

2. Since you are writing values OUT, your program will set the values, then write!!!

Opening a file (for input or output)

• always within a try/catch

|Opening a file for input(infile) |

| |

|Scanner infile = null; |

|try |

|{ |

|infile = new Scanner(new FileReader("document.txt")); |

|} catch (FileNotFoundException e) { |

|System.out.println("File not found"); |

|e.printStackTrace(); // prints error(s) |

|System.exit(0); // Exits entire program |

|} |

|Opening a file for output(outfile) |

| |

|PrintWriter outfile = null; |

|try |

|{ |

|outfile = new PrintWriter("document.txt"); |

|} |

|catch(FileNotFoundException e) |

|{ |

|System.out.println("File not found!!"); |

|e.printStackTrace(); // prints error(s) |

|System.exit(0); // Exits entire program |

|} |

Scanner infile = new Scanner(new FileReader("A:document.txt"));

• “infile” denote we are reading IN from a file

• Scanner infile; // infile becomes our “sc.next()” like variable

• FileReader("A:document.txt") // opens file for input

PrintWriter outfile = new PrintWriter("A:results.txt");

• “outfile” denote we are writing OUT to a file

YOU CAN HAVE SEVERAL FILES OPEN AT THE SAME TIME!!

The syntax to open ANY file is as follows, you have several options:

• “A:/Lupoli.txt”

• “A:Lupoli.txt”

• “Z:\\Lupoli_class\\C\\test1.txt”

• normal “\” WILL NOT WORK!!

• Why won’t this work??

o “A:\nope.txt”

Libraries to import

• import java.io.*

• import java.util.*;

Make sure input/output files are in the right place

• where the files is located to your source files makes a huge difference

|Parallel with|[pic] |

|Source |... new Scanner(new FileReader("Lupoli.txt")); |

|Inside Source|[pic] |

| |... new Scanner(new FileReader("./src/Lupoli.txt")); |

User input to open a file

• minor changes in approach

• you could also use the JOptionPane

|using strings |

|String fileName = sc.next(); |

| |

|Scanner infile = null; |

|try |

|{ |

|infile = new Scanner(new FileReader(fileName)); |

|} catch (FileNotFoundException e) { |

|System.out.println("File not found"); |

|e.printStackTrace(); // prints error(s) |

|System.exit(0); // Exits entire program |

|}// What type of file? Input/Output |

Notice “infile” “outfile” – so anything that I may have for infile, can be switched for an outfile

|(inputs from a file) infile |next (inputs from a keyboard) |

|(outputs to a file) outfile |print (outputs to the monitor) |

[pic]

To check if a file was correctly opened

• must be inside the try/catch block we are using

• THIS IS NOW A MUST

catch(FileNotFoundException e)

{

System.out.println("File not found!!");

System.exit(0);

}

Closing a file (for input or output)

• file MUST be closed when done

• important for outfile since it saves AND closes the file at the same time

• can reopen closed files

• can have several files opened

infile.close( );

outfile.close();

What does token mean?

• Item separated by a space or \n (\r)

|Actual File |Token Count |

| | |

|Lupoli is da bomb!! |4 |

|Matt failed his midterm!!! Ha Ha!!! |6 |

| | |

| | |

String Tokenizer

this String below was read in using sc.nextLine( );

|M |

|import java.util.StringTokenizer; |

|import java.io.*; |

|import java.util.*; |

| |

|public class test |

|{ |

|public static void main(String args[]) |

|{ |

| |

|//Scanner sc = new Scanner(System.in); |

|String inputline = "Lupoli is da bomb"; |

|StringTokenizer tokenizer = new StringTokenizer(inputline); |

| |

| |

|‘ create the code to determine how many token there are |

| |

|System.out.println(tokenizer.nextToken()); |

|System.out.println(tokenizer.nextToken()); |

|System.out.println(tokenizer.nextToken()); |

| |

|‘ create the code to CHECK if there is another token |

| |

|} |

| |

|} |

|What input stream is this receiving data?? (Keyboard, File, Variable) |

| |

|import java.util.StringTokenizer; |

|import java.io.*; |

|import java.util.*; |

| |

|public class test |

|{ |

|public static void main(String args[]) |

|{ |

| |

|//Scanner sc = new Scanner(System.in); |

|String inputline = "Lupoli is da bomb"; |

|StringTokenizer tokenizer = new StringTokenizer(inputline); |

| |

|while(tokenizer.hasMoreTokens()) |

|{ |

|System.out.println(tokenizer.nextToken()); |

|} |

| |

|} |

| |

|} |

Use the loop to grab each token from the string and display each token

|T |

|h |

|a |

|n |

|k |

| |

|y |

|o |

|u |

| |

|v |

|e |

|r |

|y |

| |

|m |

|u |

|c |

|h |

|! |

| |

|Scanner sc = new Scanner(System.in); |

|String inputline = sc.nextLine( ); |

|StringTokenizer tokenizer = new StringTokenizer(inputline); |

|Using a For Loop |Using a While Loop |

| | |

|for(int i = 0; i < |while( |

|{ |{ |

| | |

| | |

| | |

| | |

| | |

| | |

| | |

|} |} |

Reading from a file

• read line using sc.nextLine()

• need to use StringTokenizer

• then get data from token

String line = infile.nextLine();

StringTokenizer tokenizer = new StringTokenizer(line);

// You should know what you are reading in

// nextToken will ALWAYS be a String, need to convert

String word = tokenizer.nextToken( );

int num1 = Integer.parseInt(tokenizer.nextToken());

// tokenizer.nextToken() grabs next available token

// Integer.parseInt (coverts the token to a numeral (int) value)

|Type Name |Method for conversion |

|byte |Byte.parseByte(String_to_convert) |

|short |Short.parseShort(String_to_convert) |

|int |Integer.parseInt(String_to_convert) |

|long |Long.parseLong(String_to_convert) |

|float |Float.parseFloat(String_to_convert) |

|double |Double.parseDouble(String_to_convert) |

|char |Character(myString.charAt(0)) |

Steps for reading from a file

1. Identify types of variables you will be reading from that file

2. Next declare an uninitialized variable for each of them (above the try/catch)

|Lupoli.txt |

|23 41 address Kim |

3. Then open the file for INPUT

4. Check if the file was opened correctly

5. Read in LINE from file (below try/catch)

6. Tokenize the line

7. Close file

Using the file example above “Lupoli.txt”, use the steps above to complete your first function to read in from this file:(SLIP)

|Steps Example |

|import java.util.StringTokenizer; |

|import java.util.*; |

|import java.io.*; |

| |

| |

|public class testfile { |

| |

| |

|public static void main(String args[]) |

|{ |

| |

|int num1; |

|int num2; |

|String word1; |

|String word2; |

| |

|Scanner infile = null; |

| |

|try |

|{ |

|infile = new Scanner(new FileReader("Lupoli.txt")); |

|} catch (FileNotFoundException e) { |

|System.out.println("File not found"); |

|e.printStackTrace(); // prints error(s) |

|System.exit(0); // Exits entire program |

|} |

| |

|String line = infile.nextLine(); |

|StringTokenizer tokenizer = new StringTokenizer(line); |

| |

|infile.close(); |

| |

| |

|} |

| |

|} |

|Reading example/answer |

|// 1. & 2. Indentify type and declare |

|int num1, num2; |

|String address, name; |

| |

| |

|Scanner infile = null; |

|try |

|{ |

|// 3. |

|infile = new Scanner(new FileReader("Lupoli.txt")); |

|} catch (FileNotFoundException e) // 4. |

|{ |

|System.out.println("File not found"); |

|e.printStackTrace(); // prints error(s) |

|System.exit(0); // Exits entire program |

|} |

| |

|// 5 |

|String line = infile.nextLine(); |

| |

|// 6 |

|StringTokenizer tokenizer = new StringTokenizer(line); |

| |

|num1 = Integer.parseInt(tokenizer.nextToken()); |

|num2 = Integer.parseInt(tokenizer.nextToken()); |

|address = tokenizer.nextToken(); |

|name = tokenizer.nextToken(); |

| |

|// 7. |

|infile.close(); |

| |

|System.out.println(num1); |

|System.out.println(num2); |

|System.out.println(address); |

|System.out.println(name); |

Reading techniques

• There is a marker that tracks where you JUST read from in the file

• make sure YOU THE PROGRAMMER place a string like address at the END of a line

o easier to pull from string

• all scenarios below are AFTER:

StringTokenizer tokenizer = new StringTokenizer(line);

|Scenario #1 |

|23 41 a Luper |

|Int, int, char, string |

| |

|int num1 = Integer.parseInt(tokenizer.nextToken()); |

|int num2 = Integer.parseInt(tokenizer.nextToken()); |

|char letter = Character(tokenizer.nextToken().charAt(0)); |

|String word = tokenizer.nextToken(); // no conversion |

|Scenario #2 |

|One two three |

|String, String, String |

| |

|String word1 = tokenizer.nextToken(); // no conversion |

|String word2 = tokenizer.nextToken(); // no conversion |

|String word3 = tokenizer.nextToken(); // no conversion |

|Scenario #3 |

|Lupoli Shawn 1600 Penn… |

|String, String, String (LONG) |

| |

|String word1 = tokenizer.nextToken(); // no conversion |

|String word2 = tokenizer.nextToken(); // no conversion |

|String restOfLine = ""; |

|while(tokenizer.hasMoreTokens()) |

|{restOfLine += tokenizer.nextToken() + “ “; } |

|Scenario #4 |

|I wish Lupoli was easier |

|String (LONG) |

| |

|String restOfLine = ""; |

|while(tokenizer.hasMoreTokens()) |

|{restOfLine += tokenizer.nextToken() + “ “; } |

|// DON’T TOKENIZE THE STRING!!! sc.nextLine(); |

|Scenario #5 |

|23 Lupoli 45 Bledsoe |

|Int, String, Int, String |

| |

|int num1 = Integer.parseInt(tokenizer.nextToken()); |

|String word1 = tokenizer.nextToken(); // no conversion |

|int num2 = Integer.parseInt(tokenizer.nextToken()); |

|String word2 = tokenizer.nextToken(); // no conversion |

|Scenario #6 |

|Lohan Linday 23 1982 |

| |

| |

| |

| |

| |

| |

|Scenario #7 |

|Lupoli A A D C |

| |

| |

| |

| |

| |

Writing to a file

• Syntax – almost same as a displaying to a monitor, just a file instead

outfile.println( … ); // without it, the data will be printed on one line

outfile.println( x + “ “ + y); // you can also put multiple variables in one line

Writing different types of data

PrintWriter outfile = new PrintWriter("A:data.txt"); // opening a file for output

|writing a hard coded letter/number |writing a variable letter |

|outfile.println(‘f’); |char quit = ‘q’; |

|outfile.println(‘2’); |outfile.println(quit); |

|writing a hard coded sentence |writing a variable int |

|outfile.println( “Hello Class”); |int age = 23; |

| |outfile.println( age); |

|writing a string |

|String name = “Mr. Lupoli”; |

|outfile.println(name); // space or no space ok |

|Combining it all together |

| |

|outfile.println(“hello class, “ + name + “ “ + age + “ “ + quit); |

Breaking down a String (review)

• you can look at individual chars inside a string

o GET THE STRING AS A TOKEN using Tokenizer

• use the char functions to determine what is inside that string

o isLetter

o isDigit

o isWhitespace

o isLowerCase

o isUpperCase

String line = “Goodbye, Cruel World”;

|G |

|int count = 0; |

|for(int i = 0; i < line.length(); i++) // counts # of letters in the string |

|{ |

|if(Character.isUpperCase(line.charAt(i))){ count++; } |

|} |

|System.out.println(count); |

|isDigit example |

|int count = 0; |

|for(int i = 0; i < line.length(); i++) // counts # of numbers in the string |

|{ |

|if(Character.isDigit(line.charAt(i))){ count++; } |

|} |

|System.out.println(count); |

Steps for writing to a file

1. Identify types of variables you will be writing OUT to that file, unless you want to hard code an output

2. Identify the ORDER you wish to place the data to the file

3. Next declare an initialized variable for each of them

4. Then open the file for OUTPUT

5. Write data

6. Close file

Where do I put the file to read in, or to output?

• That is up to you as a programmer OR up to the user (if you ask them)

• Simple way

o A:

o F: (thumb)

o Drive not specified (“document.txt”)

▪ Means RIGHT beside the .cpp file you are creating

Using a While loop to read data continually

|89 |

|98 |

|66 |

|54 |

|97 |

|34 |

|98 |

| |

| |

|int scores = 0; |

|while(infile.hasNextLine()) |

|{ |

|String line = infile.nextLine(); |

|StringTokenizer tokenizer = new StringTokenizer(line); |

|// You should know what you are reading in |

| |

|scores = scores + Integer.parseInt(tokenizer.nextToken()); |

|} |

While Loops

|Flow Layout |Notes |

|5[pic] |Things to Notice : |

| |• Make sure { }’s are in Block Like structure!!! |

| |• The initializing variable is BEFORE the loop |

| |• The initializing variable is set so that the loop will run |

| |• used when NOT exactly sure when loop should or will end, or when the USER will define when to end |

|(Counter) |(Event Controlled) |

|//initialization |//initialization |

|int count = 0; | |

| |while (infile.hasNextLine()) |

|while (count ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download