Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner vs FileInputStream

Tags:

java

io

eclipse

Scanner scanner= new Scanner(new File("target.txt"));

and

FileInputStream d = new FileInputStream("target.txt");

What is the difference between Scanner.nextByte() and FileInputStream.read() ?

I am trying to understand it because when i read bytes (one by one) from a file with simple text with the FileInputStream it works fine. But when iam using Scanner the scanner.nextByte() doesn't return anything?

Why is that?

like image 915
Tony Avatar asked Feb 02 '26 20:02

Tony


1 Answers

The Scanner.nextByte() will read the next token and if it can be evaluated as a byte then return it while FileInoutStream.read() will return each byte of a file. Consider this example:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class SO {
  public static void scanner() throws FileNotFoundException {
    System.out.println("Reading with the Scanner Class:");
    Scanner scanner= new Scanner(new File("target.txt"));
    while(scanner.hasNext()) {
      try {
        System.out.println("A Byte:"+scanner.nextByte());
      } catch(InputMismatchException e) {
        System.out.println("Not a byte:"+scanner.next());
      }
    }
    scanner.close();
  }

  public static void stream() throws IOException {
    System.out.println("Reading with the FileInputStream Class:");
    FileInputStream d = new FileInputStream("target.txt");
    int b = -1;
    while((b = d.read()) != -1) {
      System.out.print((byte)b+" ");
    }
    d.close();
    System.out.println();
  }

  public static void main(String...args) throws IOException {
    scanner();
    stream();
  }
}

With this as the contents of target.txt:

Next up is a byte:
6
Wasn't that fun?

This will produce the following output:

Reading with the Scanner Class:
Not a byte:Next
Not a byte:up
Not a byte:is
Not a byte:a
Not a byte:byte:
A Byte:6
Not a byte:Wasn't
Not a byte:that
Not a byte:fun?
Reading with the FileInputStream Class:
78 101 120 116 32 117 112 32 105 115 32 97 32 98 121 116 101 58 10 54 10 87 97 115 110 39 116 32 116 104 97 116 32 102 117 110 63 
like image 153
Jason Sperske Avatar answered Feb 05 '26 08:02

Jason Sperske