Savitch 10.1-10.3
System.in is an input stream that reads data from the keyboard.System.out is an output stream that sends data to the screen.PrintWriter class.
1
2
3
4
5
6
7
8
9
String fileName = "out.txt"; // the name of the file
PrintWriter outputStream = null; // the stream variable
try { // constructor must be invoked in a try block
outputStream = new PrintWriter(fileName); // create and open the file
}
catch (FileNotFoundException e) { // problem creating/opening the file
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
PrintWriterand FileNotFoundExceptionmust be imported from the java.iopackage.println, printor printfjust like System.out.
1
2
outputStream.println("This is line 1.");
outputStream.println("This is line 2.");
PrintWriter writes data to a buffer buffer in memory, which can be written to the file when it full or the stream is closed.close method.
1
outputStream.close()
PrintWriter
PrintWriterobject is declared in a tryblock, it can only be used in the tryblock.toStringmethod can be passed to any of the PrintWriterfile writing methods.PrintWriterconstructor, all of its data will be erased and it will become an empty text file.FileOutputStreamobject.PrintWriterconstructor.
1
outputStream = new PrintWriter(new FileOutputStream(filename, true));
FileOutputStreamconstructor indicates data should be written to the end of the existing file.tryblock with a catchblock that handles a FileNotFoundException.FileOutputStreamclass must also be imported from the java.iopackage.Fileobject.Scannerconstructor.
1
2
3
4
5
6
7
8
9
String fileName = "out.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName)); // opens the file
}
catch(FileNotFoundException e) { // file is not accessible or does not exist
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
Fileclass must also be imported from the java.io package.Scannermethods used to read data from the keyword.hasNextLine()method can be used to determine if the Scannerhas reached the end of the file.
1
2
3
4
while(inputStream.hasNextLine()) { // loop until end of file is reached
String line = inputStream.nextLine(); // read the next line
System.out.println(line); // write the line to the screen
}
closemethod of the Scannerclass.
1
inputStream.close();
File
Filerepresents file names in a general way.
1
File myFile = new File("treasure.txt");
Stringas a file name, but others will only accept a Fileobject.
PrintWriter constructor accepts a File, a String, or a OutputStream.Scanner constructor accepts a File or an InputStream.FileOutputStreamconstructor accepts a Fileor a String.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
System.out.println("Enter file name");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next(); // read the file name from the keyboard
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
}
catch (FileNotFoundException e) {
System.out.println("error opening the file " + fileName");
System.exit(0);
}
String line = inputStream.nextLine(); // read a line from file
System.out.println(line);
inputStream.close();
/and /is used as separator.
1
/user/smith/homeword1/data.txt
C:\and \is used as a separator.
1
C:\homework\hw1\data.txt
\\or /must be used.
1
2
"C:\\homework\\hw1\\data.txt"
"C:/homework/hw1/data.txt"
File
1
2
3
4
5
6
7
8
9
10
11
12
13
14
File fileObject = new File(fileName);
boolean fileOK = false;
while (!fileOK) {
if(!fileObject.exists()) // checks if there is a file with that name
System.out.println("No such file");
else if (!fileObject.canRead()) // checks if the file can be opened for reading
System.out.println("That file is not readable.");
else
fileOK = true;
if (!fileOK) {
System.out.println("Enter file name again: ");
fileObject = new File(keyboard.next());
}
}
1
2
3
4
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
return new PrintWriter(fileName);
}
void method:
1
2
3
4
public static void openFile(String fileName, PrintWriter stream)
throws FileNotFoundException {
stream = new PrintWriter(fileName);
}
openFilemethod will not change the original PrintWriter object passed as an argument.Transactions.txtthat contains records of each of the sales entered in a cash register.
1
2
3
4
5
SKU,Quantity,Price,Description
4039,50,0.99,SODA
9100,5,9.50,T-SHIRT
1949,30,110.0,JAVA PROGRAMMING TEXTBOOK
5199,25,1.50,COOKIE
1
2
String line = "4039,50,0.99,SODA";
String array = line.split(","); // use , as a delimiter
Integer.parseInt and Double.parseDoublemethods to convert the strings to numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class TransactionReader {
public static void main(String[] args) {
String fileName = "Transactions.txt";
try {
Scanner inputStream = new Scanner(new File(fileName));
String line = inputStream.nextLine(); // skip header line
double total = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
String[] transaction = line.split(",");
String SKU = transaction[0];
int quantity = Integer.ParseInt(transaction[1]);
double price = Double.parseDouble(transaction[2]);
System.out.printf("Sold %d of %s (SKU: %s) at $%1.2f each. \n",
quantity, description, SKU, price);
total += quantity * price;
}
System.out.printf("Total sales: $%1.2f\n", total);
inputStream.close();
catch(FileNotFoundException e) {
System.out.println("Cannot find file " + filename);
}
catch(IOException e) {
System.out.println("Problem with input from file " + fileName);
}
}