Switch statementTopGUI componentsSimple Java I/O

Simple Java I/O

Java has a fairly sophisticated I/O system that allows you to read and write across the internet as easily as reading and writing to the console or a local file. However, there is also a simple implementation of I/O that will serve for most purposes.

At the beginning of this tutorial we discussed System.out.print and System.out.println. They will output their parameter (and if using println, start a new line afterward). In the rest of this section we discuss the Scanner class.

To hook up console (keyboard) input to your program, begin by creating a scanner:

   Scanner scan = new Scanner(System.in);

System.in is the Java name for keyboard input. If instead you want to read from a file on your hard drive (in the same folder as your program), you can create a scanner for the file myText.txt with

   Scanner scanfile = new Scanner(new File("myText.txt"));

Scanner objects have methods to read ints, doubles, booleans, Strings and more. Here are corresponding method specifications:

   int nextInt()
   double nextDouble()
   boolean nextBoolean()
   String next()
   String nextLine()

For example, scan.nextInt() will return the next int typed into the console. Generally the scanner breaks the input into tokens, which are strings separated by white space (e.g., spaces, tabs, or returns) in the input. Thus we can read (and then print) an int followed by a String with

   System.out.println(scan.nextInt());
   System.out.println(scan.next());

You can test to see if there is another token in the input with hasNext(). You can test if the next token is an int using hasNextInt() and similarly for other built-in types. Each returns a boolean.

The method nextLine() differs from the others in that it reads everything on the input line until the return and then returns everything before the return. Thus it differs from next() in that it doesn't stop when it encounters white space, it just gobbles everything until the end of the line.

If you wish to write to a text file, you create a PrintWriter and send it print or println method requests.

   PrintWriter myWriter = new PrintWriter("myText.txt")

and write using myWriter.print("Some text to print") or using println if you want it to terminate with a return.


Switch statementTopGUI componentsSimple Java I/O