Java has the following classes commonly used for input:
Scanner
FileReader
BufferedReader
Input via Scanner
Initialising
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
}
}
We need to import the Scanner package before using scanner. Create a Scanner Object using the Scanner Constructor
Scanner()
constructor takes either a FileStream
or File
as it’s arguments. Here, System.in
is the default input stream from the terminal/console.
Methods
Scanner.nextLine()
: Reads and returns an entire line, stopping only when it reaches a line terminator such as\n
,\t
etc.Scanner.next[DATATYPE]()
: Scanner has many methods likenextInt()
,nextDouble()
,nextBoolean()
, which all read until they find the specified data type, and then return said data.Scanner.hasNext()
: Boolean that checks if any input that can be read is left.Scanner.hasNext[DATATYPE]()
: Boolean that only returns true if there exists a[DATATYPE]
left to read. For example,Scanner.hasNextInteger()
will only return true if an integer is given to it.
Input via FileReader
Java implements all it’s classes related to file input and output in the java.io
package.
The FileReader
class to allow reading of simple .txt
files. It is a very basic class, and only supports reading characters, which can be stored into an array. The FileReader
object can be constructed with either a FILEPATH
String or a File
Object.
import java.io.FileReader;
//FileReader using String filepath
FileReader reader = new FileReader("testfile.txt");
File file = new File(); //Assume this File object is created properly
//FileReader using File object
FileReader reader2 = new FileReader(file);
//Array MUST be of type char
char arr[300];
//Reads data from testfile.txt and stores into arr array
reader.read(arr);
//Prevents further reading.
reader.close();
Best practice
The most common practice is to wrap another class such as
Scanner
(though this is slow for large files), orBufferedReader
aroundFileReader
.
Input via BufferedReader
BufferedReader
is a more powerful version of FileReader
. It allows reading of Strings instead of just chars.
Generally, this class wraps around FileReader
, as such:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
BufferedReader
comes with many useful methods:
import java.io.BufferedReader;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
//Supports char reading, just like FileReader
char c = br.read();
//Stores the next line into the text array
String text = br.readLine();
//Can skip x characters as well!
br.skip(5);