PrintWriter for output, Scanner for
inputFile file = new File ("object.dat");
Use PrintWriter to write text files
new PrintWriter(new File("output.txt"))
PrintWriter out = new PrintWriter("output.txt"));print() and println() methods
out.println(45.71);
out.println(new Rectangle(10, 20, 100, 50));
out.print("Hello, SJSU");out.close()
Use Scanner to read text files
Scanner in = new Scanner( new File("input.txt"));
in.next()
in.nextInt()
or in.nextDouble()
in.nextLine()
in.close();
1729 Harry 1730 Wilma
int studentID = in.nextInt();

nextLine, you don't read Harry.
Reads an empty string! nextLine after reading the ID:
int studentID = in.nextInt();
in.nextLine(); // Consume the \n
String name = in.nextLine();
Suppose the input contains the characters 2nd place. What is the
value of number and word after these statements?
int number = in.nextInt(); String word = in.next();
public static void main(String[] args)
throws FileNotFoundException
while (in.hasNextLine())
{
String line = in.nextLine();
//processing
}
if (in.hasNextInt())
{
int number = in.nextInt();
//processing
}
Scanner in = new Scanner(. . .);
in.useDelimiter("[^A-Za-z]+");
...When the file is line oriented but contains mixed data:
China 1330044605 United States 303824646 ...
String line = in.nextLine(); Scanner lineIn = new Scanner(line); String country = lineIn.next(); while (!in.hasNextDouble()) country = country + " " + lineIn.next(); double area = lineIn.nextDouble();
while keeps concatenating words until a double is foundWhen the numeric data contain non-numeric characters like $
China $13344605 N/A United States $303824646 $46,000 ...
An input file contains lines such as
Fred 40 Wilma 28 Mary Ann 30
Consider this code to process a line:
String line = in.nextLine();
int n = line.lastIndexOf(' ');
String name = line.substring(0, n);
int age = Integer.parseInt(line.substring(n));
What is the problem with this code?
Integer.parseInt throws an exception| F | r | e | d | 4 | 0 | |
|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
int age = Integer.parseInt(line.substring(n).trim());
int age = Integer.parseInt(line.substring(n + 1));
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
{
throw new IllegalArgumentException("Amount exceeds balance");;
}
balance = balance - amount;
}
. . .
}
Special Topic 11.3 on the web
java -classpath build/classes programName
java -classpath build/classes programName string1 string2 ...
if (args.length > 0)
{
fileName = args[0]
...
}
else
System.out.println("Usage java programName string1");