Java IO

Reading console input

Scanner in = new Scanner(System.in);
String name = in.nextLine(); // to read a line
String firstName = in.next(); //next word
int age = in.nexctInt(); // to read an integer

Formatting output

System.out.printf("Hello %s. Your age: %d.", name, age);

//create a formatted string without printing it
String msg = String.format("Hello %s. Your age: %d.", name, age);\

/*2$ means the 3nd argument used, 
  < means the same argument as in the preceding format specification used
  t means next character is conversion character,
  B, e and Y are Date conversion character */
System.out.printf("%1$s %2$tB %<te %<tY", "Due data: ", new Date());

File Input and Output

Scanner in = new Scanner(Paths.get("c:\\dir\\file.txt"));

PrintWriter out = new PrintWriter("file.txt"); // if it does not exist, create it

java.io has two major parts: character(URF-16) streams and byte(8 bits) streams. The byte streams are called input streams and output streams, and the character streams are called readers and writers.

The object serialization mechanism, which transforms objects into byte streams and allows objects to be reconstituted from the data read from a byte stream.

Last Updated 2015-11-14 Sat 20:50.

Created by Howard Hou with Emacs 24.5.1 (Org mode 8.2.10)