Skip to content
UoL CS Notes

Input & Output (I/O) - 2

COMP122 Labs

There are many I/O classes, view the full Oracle I/O tutorial here.

Scanner

java.util.Scanner splits up an input into tokens that can be read one at a time.

You can scan through these using the has.Next() and look for specific types using other methods:

double sum = 0;
try (Scanner scan = new Scanner("20.40 notadouble 30.45 gawef 49.15")) {
	while(scan.hasNext()) {
		if(scan.hasNextDouble()) {
			sum += scan.nextDouble();
		}
		else {
			scan.next();
		}
	}
}
System.out.println(sum);

By using a try with resource, Java will close the Scanner after is is finished being used.

Scanner vs Reader

Scanner has pretty all of the functionality of BufferedReader, including a nextLine() function that allows you to break up a file line by line and skip the remaining tokens on a given line. That said, it is slower and more expensive than BufferedReader, which is the preferred option if you just want text. Further, the nextLine() functionality can make the scanning process messy, as it can potentially skip a lot of tokens, and was not really designed for the use case we discussed last week. A common use case is thus to use a BufferedReader to read a file in as Strings, and then use a Scanner to break these Strings into tokens.

BufferedWriter

To write to a file you can use the following example code:

String test = "This is a test."
try(BufferedWriter bw = Files.newBufferedWriter(outPath)) {
	bw.write(test);
}

By using a try with resource, the file is written out when the try has executed.

To force the buffer to be written use bw.flush().

You should avoid closing the stream until you are sure that you are done writing to a file.