File I/O
Strings and File I/O
String Functions
|Method Summary |
| char |charAt(int index) |
| | Returns the char value at the specified index. |
|String word = “Apple”; |
|char letter = word.charAt(2); // p |
| |
|if(type.charAt(0) = = 'M') // in comparing with a char CAN USE = = |
| int |codePointAt(int index) |
| | Returns the character (Unicode code point) at the specified index. |
| int |compareTo(String anotherString) |
| | Compares two strings lexicographically. |
|if(pareTo(two)) |
|if(pareTo(“Kristen”)) |
|if(“Kristen”.compareTo(one)) // WILL NOT WORK!! |
| |
|Values compareTo( ) returns |
| |
|returns |
|when |
|example |
| |
|< 0 |
|string1 alphabetically/ASCII before string2 |
|“cat”, “dog” |
| |
|0 |
|string1 alphabetically/ASCII INDENTICAL string2 |
|“dog”, “dog” |
| |
|> 0 |
|string1 alphabetically/ASCII” after string2 |
|“dog”, “cat” |
| |
| |
| int |compareToIgnoreCase(String str) |
| | Compares two strings lexicographically, ignoring case differences. |
| String |concat(String str) |
| | Concatenates the specified string to the end of this string. |
| boolean |contains(CharSequence s) |
| | Returns true if and only if this string contains the specified sequence of char values. |
| boolean |contentEquals(CharSequence cs) |
| | Returns true if and only if this String represents the same sequence of char values as the specified sequence. |
| boolean |contentEquals(StringBuffer sb) |
| | Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. |
| boolean |endsWith(String suffix) |
| | Tests if this string ends with the specified suffix. |
| boolean |equals(Object anObject) |
| | Compares this string to the specified object. |
|if(one.equals(two)) |
|if(one.equals(“Kristen”)) |
|if(“Kristen”.equals(one)) // WILL NOT WORK!! |
| |
|Values equals( ) returns |
| |
|returns |
|when |
|example |
| |
|0 |
|string1 NOT IDENTICAL to string2 |
|“cat”, “dog” |
| |
|1 |
|string1 INDENTICAL string2 |
|“dog”, “dog” |
| |
| |
|Algorithm matches EACH letter until there is a difference. |
|(What we do when finding people in a telephone book) |
| boolean |equalsIgnoreCase(String anotherString) |
| | Compares this String to another String, ignoring case considerations. |
| int |indexOf(int ch) |
| | Returns the index within this string of the first occurrence of the specified character. |
| int |indexOf(int ch, int fromIndex) |
| | Returns the index within this string of the first occurrence of the specified character, starting the search at the specified |
| |index. |
| int |indexOf(String str) |
| | Returns the index within this string of the first occurrence of the specified substring. |
|[0] |
|[1] |
|[2] |
|[3] |
|[4] |
|[5] |
| |
|L |
|u |
|p |
|o |
|l |
|i |
| |
|indexOf = find FIRST occurrence |
| |
|String professor = “Lupoli”; |
|int x = professor.indexOf(“oli”); // return index its starts at |
|// 3 |
| int |indexOf(String str, int fromIndex) |
| | Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. |
| int |lastIndexOf(int ch) |
| | Returns the index within this string of the last occurrence of the specified character. |
| int |lastIndexOf(int ch, int fromIndex) |
| | Returns the index within this string of the last occurrence of the specified character, searching backward starting at the |
| |specified index. |
|[0] |
|[1] |
|[2] |
|[3] |
|[4] |
|[5] |
|[6] |
|[7] |
|[8] |
| |
|l |
|o |
|l |
|l |
|i |
|p |
|o |
|p |
|s |
| |
|lastIndexOf = find LAST occurrence |
| |
|String lollipop = “lollipop”; |
|int x = lollipop.lastIndexOf(“p” , 8); // return index its starts at |
|// 7 |
| |
|What index will be returned for the function call: lollipop.rfind(“l”, 1)?? |
| int |lastIndexOf(String str) |
| | Returns the index within this string of the rightmost occurrence of the specified substring. |
| int |lastIndexOf(String str, int fromIndex) |
| | Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the |
| |specified index. |
| int |length() |
| | Returns the length of this string. |
|String String1 = “Apple”; |
|A |
|p |
|p |
|l |
|e |
| |
|System.out.println(String1.length( )); // displays 5 |
| String |replace(char oldChar, char newChar) |
| | Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. |
| String |replace(CharSequence target, CharSequence replacement) |
| | Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. |
| boolean |startsWith(String prefix) |
| | Tests if this string starts with the specified prefix. |
| boolean |startsWith(String prefix, int toffset) |
| | Tests if this string starts with the specified prefix beginning a specified index. |
| String |substring(int beginIndex) |
| | Returns a new string that is a substring of this string. |
|String greeting = “Hello There”; |
|String new_String = greeting.substring(6); // will get “There” |
| String |substring(int beginIndex, int endIndex) |
| | Returns a new string that is a substring of this string. |
|String greeting = “Hello There”; |
|H |
|e |
|l |
|l |
|o |
| |
|T |
|h |
|e |
|r |
|e |
| |
|String new_String = greeting.substring(0, 4); // will get “Hell” |
| char[] |toCharArray() |
| | Converts this string to a new character array. |
| String |toLowerCase() |
| | Converts all of the characters in this String to lower case using the rules of the default locale. |
|String greeting = “Hello Class”; |
|greeting = greeting.toLowerCase(); // now makes greeting “hello class” |
| String |toString() |
| | This object (which is already a string!) is itself returned. |
| String |toUpperCase() |
| | Converts all of the characters in this String to upper case using the rules of the default locale. |
|String greeting = “Hello Class”; |
|greeting = greeting.toUpperCase(); // now makes greeting “HELLO CLASS” |
| String |trim() |
| | Returns a copy of the string, with leading and trailing whitespace omitted. |
|String statement = “ Mr. L is da bomb ”; |
|statement = statement.trim(); // statement now is”Mr. L is da bomb”; |
|static String |valueOf(char c) |
| | Returns the string representation of the char argument. |
|static String |valueOf(char[] data) |
| | Returns the string representation of the char array argument. |
|static String |valueOf(char[] data, int offset, int count) |
| | Returns the string representation of a specific subarray of the char array argument. |
|static String |valueOf(double d) |
| | Returns the string representation of the double argument. |
|static String |valueOf(float f) |
| | Returns the string representation of the float argument. |
|static String |valueOf(int i) |
| | Returns the string representation of the int argument. |
|static String |valueOf(long l) |
| | Returns the string representation of the long argument. |
|static String |valueOf(Object obj) |
| | Returns the string representation of the Object argument. |
Concatenation
String String1 = “Goodbye”;
String String2 = “, Cruel ”;
String1 = String1 + String2;
String1 = String1 + “World!”;
// String1 now contains “Goodbye, Cruel World!”
|G |
|Scanner sc = new Scanner(System.in); |
|String inputline = sc.readLine( ); |
|StringTokenizer tokenizer = new StringTokenizer(inputline); |
|Using a For Loop |Using a While Loop |
| | |
|for(int i = 0; i < |while( |
|{ |{ |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|} |} |
Converting Strings to Numbers
There will be many times were the input interface will treat whatever the user types in as a String, (JOptionPane), we can then transform that input into the format intended.
String x;
int real_number;
x = JOptionPane.showDialog(“Enter a whole number:”); // “x” is a STRING 23
realnumber = Integer.parseInt(x); // now “realnumber” is actually an INT value 23
|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) |
Array of Strings
String [] nameOfDay = { // Array of 7 string
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
Sunday Tuesday Thursday Saturday
0 1 2 3 4 5 6
| | | | | | | |
Monday Wednesday Friday
System.out.println(nameOfDay[5]); // displays “Friday”
Finding a “null” or “” in a array of Strings
• you might find that an array element do not contain viable data
• do find, use the “.eguals()” string command
• commonly mistaken what to do
|Common search errors |
|String |String in an Array |
| |if(answers[i] != "") { length++; } |
| |if(answers[i] != " ") { length++; } if(answers[i] != null) { length++; } |
| |if(answers[i] != "null") { length++; } |
|Correct null search code |
|String |String in an Array |
|String type = answers[i]; |if(!answers[i].equals("") ) { length++; } |
|if(type == null ) | |
Try/catch Blocks
• These will contain/recover from errors so not to END your entire application
o used for many items such as:
▪ File I/O
▪ Input from the keyboard
• an error is called an EXCEPTION
o there are many methods we use the THROW an exception
• try and catch and finally are reserved words
o try -> “try to do something that may cause an error”
o catch -> “catch that error”
▪ you can have SEVERAL “catches”
o finally -> “do no matter what”
• structure is exactly the same an if-else-if
o if ( Try
o else if ( catch(es)
o else ( finally
|Try/Catch structure |
|try |
|{ |
|// code that may generate an exception |
|} |
|catch(Exception’s_Class alias) |
|{ |
|// code to recover from the error |
|} |
|finally // OPTIONAL |
|{} |
• great example would be if a user typed in a character instead of an integer
o from Java 5 Illuminated by Anderson and Franceschi
|Code without error checking |
|// must import javax.swing.JOptionPane; |
|public static void main(String [] args) |
|{ |
|String s = JOptionPane.showInputDialog(null, “Enter an Integer:”); |
|System.out.println(“You entered “ + s); |
| |
|int x = Integer.parseInt(s); |
|System.out.println(“Conversion was successful. The integer is “ + x); |
|} |
|Correct Data Entered |Incorrect Data Entered |
|[pic] |[pic] |
|[pic] |[pic] |
|Code with error checking |
|public static void main(String [] args) |
|{ |
|String s = JOptionPane.showInputDialog(null, “Enter an Integer:”); |
|System.out.println(“You entered “ + s); |
| |
|try |
|{ |
|int x = Integer.parseInt(s); |
|System.out.println(“Conversion was successful. The integer is “ + x); |
|} |
|catch(NumberFormatException z) |
|{ |
|System.out.println(“Conversion NOT successful, incompatible types.”); |
|z.printStrackTrace(); // prints error message |
|} |
|} |
Create a program that will accept test scores (0-100) and average the scores when the user types ANY letter to end inputting. (use the try/catch block to your advantage)
public static void main(String [] args)
{
}
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 |
Library Files needed for File I/O
• import java.io.*;
o other books may specify EXACT libraries needed
Opening a file for Output
BufferedWriter outfile = new BufferedWriter(new FileWriter("A:document.txt"), false);
• in this one line we are actually doing 3 things:
o BufferedWriter outfile; // outfile becomes our file variable
o FileWriter("A:document.txt") // opens file
o MUST BE INSIDE A TRY BLOCK (shown below)
o FALSE MEANS WE ARE NOT APPENDING TO THE FILE
• outfile
o is a variable that we will use to access the file
o variable name I pick so I know we are writing OUT to a file
o will need ANOTHER name if you need to open another file at the same time
The syntax to open ANY file is as follows, you have several options:
• “A:/Lupoli.txt”
• “Z:\\Lupoli_class\C\test1.txt”
• normal “\” WILL NOT WORK!!
User input to open a file for OUTPUT
String filename;
System.out.println(“Please type the file to open:”);
filename = sc.readLine( );
BufferedWriter outfile = null;
try // must use a try block
{
outfile = new BufferedWriter(new FileWriter(filename), false);
…
to check if a file was correctly opened
BufferedWriter outfile = null; // must do this OUTSIDE of try block
try
{
outfile = new BufferedWriter(new FileWriter(“A:document.txt”), false);
}
catch(FileNotFoundException e) // will catch error
{
System.out.println(“File not found!!!”);
System.exit(0);
}
Writing to a file
|Method Summary for BufferedWriter |
| void |close() |
| | Close the stream. |
| void |flush() |
| | Flush the stream. |
| void |newLine() |
| | Write a line separator. |
| void |write(char[] cbuf, int off, int len) |
| | Write a portion of an array of characters. |
| void |write(int c) |
| | Write a single character. |
| void |write(String s, int off, int len) |
| | Write a portion of a String. |
outfile.write(“Greeting Mr. L”); outfile.newLine();
// newline will act as a carriage return
// without it, the data will be printed ALL on one line
String name;
name = sc.readLine( );
outfile.write(“Greeting “ + name); // using ANY TYPE of variables
Lupoli.txt
|Greeting Chris |
| |
| |
String first, last;
first = sc.readLine( );
last = sc.readLine( );
outfile.write(“Hello” + first + last); // you can also put multiple variables in one line
Lupoli.txt
|Hello Jack McLaughlin |
| |
| |
Closing a file (for input or output)
outfile.close( );
• then you could reopen the file, at it will start from the beginning again!!
• ALWAYS need to close a file when done!!!!
• WILL NOT SAVE WORK THAT YOU WROTE!!!!
Steps for writing to a file
1. First step is to know types of variables you will be writing out to that file, unless you want to hard code an output
2. Next declare them
3. Then open the file for OUTPUT
4. Write data
5. Close file
Opening a file for INPUT
BufferedReader infile = new BufferedReader(new FileReader("A:document.txt"));
• in this one line we are actually doing 2 things:
o BufferedReader infile; // infile becomes our file variable
o FileReader("A:document.txt") // opens file
• infile
o is a variable that we will use to access the file
o variable name I pick so I know we are writing IN to a file
o will need ANOTHER name if you need to open another file at the same time
User input to open a file for INPUT
String filename;
System.out.println(“Please type the file to open:”);
filename = sc.readLine( );
BufferedReader infile = new BufferedReader(new FileReader(filename));
To check if a file was correctly opened
BufferedReader infile;
try
{
infile = new BufferedReader(new FileReader("A:document.txt"));
}
catch(FileNotFoundException e) // will catch error
{
System.out.println(“File not found!!!”);
System.exit(0);
}
Reading from a file
IS VERY DIFFERENT THAN WRITING TO A FILE!!!
1. In reading a file, you must read in EACH LINE ENTIRELY!!
2. That line may have several different values, and data types
3. You will need to STRING TOKENIZE AND CONVERT those values into what you need (Tokenizing is in STRINGS notes)
4. Again you must know what you are reading in to tokenize anything, or get any value from this!!!
To read in each line you use the readLine command
|name |description |
|readLine() |Reads a line of text and returns that line as a String value. |
but THIS readline command actually comes from the BufferedReader Class!!!
Lupoli.txt
|Hello Jack McLaughlin |
| |
| |
| |
try // must have a catch
{
String line;
BufferedReader infile = new BufferedReader(new FileReader("A:Lupoli.txt"));
line = infile.readLine( ); // reads first line from file Lupoli.txt
System.out.println(line); // prints line read in to screen
}
catch (IOException e)
{
System.err.println("Couldn't read from File");
System.exit(1);
}
YOU WOULD NEED TO TOKENIZE THE “LINE” TO GET THE SEPARATE VALUES OF:
hello Jack McLaughlin
Create a function to Tokenize the “line” into the string greeting, first, and last:
Steps for reading from a file
1. First step is to know types of variables you will be writing out to that file, unless you want to hard code an output
2. Next declare them
3. Then open the file for OUTPUT
4. Write data
5. Close file
Using a While loop to read data continually
• FULL BLOWN EXAMPLE
• import java.util.StringTokenizer;
|89 |
|98 |
|66 |
|54 |
|97 |
|34 |
BufferedReader infile;
String line = "";
try
{
infile = new BufferedReader(new FileReader("test.txt"));
line = infile.readLine();
while (line != null)
{
//System.out.println(line);
// prints line read in to screen
// rest of code
StringTokenizer token = new StringTokenizer(line);
String input = token.nextToken(); // gets next value in String
// rest of code
…
// this line must be the last line
line = infile.readLine( ); // reads first line from file to be checked
}
}
catch(IOException e) // will catch error
{
System.out.println("File not found!!!");
System.exit(0);
}
infile.close( ); // must use to save data written!!!
Period8.txt
|Wegner Keith 70 60 |
|Wong Alex 30 10 |
|Allen Rodney 99 23 |
|Meehan Mike 23 56 |
Create a function that will read the data from this file.
Using a While loop to WRITE data continually
• This example uses a ARRAYLIST to hold the data we are about to write
o should use SOME type of data holder
BufferedWriter outfile = null; // must do this OUTSIDE of try block
try
{
outfile = new BufferedWriter(new FileWriter("LZWencoded.txt"));
for(int i = 0; i < c.size(); i++)
{
outfile.write(":" + c.elementAt(i) + ":"); outfile.newLine();
System.out.println("yoo");
}
}
catch(FileNotFoundException e) // will catch error
{
System.out.println("File not found!!!");
System.exit(0);
}
outfile.close( ); // must use to save data written!!!
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- how can i file my own taxes
- file i o in java
- should i file bankruptcy quiz
- o i super heavy tank
- can i file 2018 taxes online
- can i file past taxes online
- can i still file 2018 taxes online
- how do i open file history
- i forgot to file 2nd quarter 941
- do i file a 1098 t form
- how do i file disability
- can i file a 941 electronically