Java Utililty Methods Scanner Read

List of utility methods to do Scanner Read

Description

The list of methods to do Scanner Read are organized into topic(s).

Method

StringreadFile(File file)
read File
StringBuilder fileContents = new StringBuilder();
Scanner scanner;
try {
    scanner = new Scanner(file, "UTF-8");
} catch (FileNotFoundException e) {
    e.printStackTrace();
    return null;
String lineSeparator = System.getProperty("line.separator");
try {
    while (scanner.hasNextLine()) {
        fileContents.append(scanner.nextLine() + lineSeparator);
    return fileContents.toString();
} finally {
    scanner.close();
StringreadFile(File file)
read File
Scanner scan;
try {
    scan = new Scanner(file);
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
    return null;
String content = scan.useDelimiter("\\Z").next();
...
StringreadFile(File input)
Reads a file and outputs it as String
StringBuilder fileBuffer = new StringBuilder((int) input.length());
Scanner scanner = new Scanner(input);
try {
    while (scanner.hasNextLine()) {
        fileBuffer.append(scanner.nextLine()).append('\n');
} finally {
    scanner.close();
...
StringreadFile(File path)
read File
try {
    return new Scanner(path, "UTF-8").useDelimiter("\\A").next();
} catch (FileNotFoundException ex) {
    return null;
StringreadFile(final File f)
read File
String s = null;
if (f.exists()) {
    s = new Scanner(f).useDelimiter("\\A").next();
return s;
ArrayListreadFile(String file_name)
read File
ArrayList<String> list = null;
Scanner scanner;
try {
    list = new ArrayList<String>();
    scanner = new Scanner(new FileInputStream(file_name));
    while (scanner.hasNext()) {
        list.add(scanner.nextLine());
    scanner.close();
} catch (FileNotFoundException ex) {
    return null;
return list;
StringreadFile(String filename)
Reads a certain file of a path.
StringBuilder content = new StringBuilder();
try {
    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(new FileInputStream(filename));
    try {
        while (scanner.hasNextLine()) {
            content.append(scanner.nextLine() + NL);
    } finally {
        scanner.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
return content.toString();
ListreadFile(String fileName)
read File
Scanner s = new Scanner(new File(fileName));
List<String> list = new ArrayList<String>();
while (s.hasNext()) {
    list.add(s.next());
s.close();
return list;
StringreadFile(String fileName)
read File
return new Scanner(new File(fileName)).useDelimiter("\\A").next();
StringreadFile(String fileName)
Reads a file relative to the CMPUT391 directory and returns a String.
File inFile = new File("catalina/webapps/CMPUT391F/" + fileName);
String out = "";
Scanner scanner = new Scanner(new FileInputStream(inFile));
out = scanner.useDelimiter("\\Z").next();
return out;