A2oz

What is the difference between Scanner and DataInputStream?

Published in Java Input/Output 2 mins read

Both Scanner and DataInputStream are classes in Java used for reading data from input streams. However, they differ in their primary functions, strengths, and how they handle data.

Scanner

  • Focus: Designed for reading data in a human-readable format, such as strings, numbers, and delimited data.
  • Strengths: Offers convenient methods for parsing various data types (e.g., nextInt(), nextDouble(), nextLine()), making it ideal for interactive input and file parsing.
  • Limitations: Can be less efficient for large binary data files.

DataInputStream

  • Focus: Primarily designed for reading binary data, such as primitive data types and objects serialized in a binary format.
  • Strengths: Provides methods for reading primitive types (e.g., readInt(), readDouble(), readUTF()), making it suitable for handling raw data.
  • Limitations: Less intuitive for parsing human-readable data compared to Scanner.

Key Differences

Feature Scanner DataInputStream
Purpose Reading human-readable data Reading binary data
Data Types Strings, numbers, delimited data Primitive data types, serialized objects
Efficiency Efficient for smaller files and parsing Efficient for large binary data files
Ease of Use User-friendly methods for parsing data Requires more manual data handling

Example

Scanner:

Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
String name = scanner.nextLine();
System.out.println("Name: " + name + ", Age: " + age);

DataInputStream:

DataInputStream dataInputStream = new DataInputStream(new FileInputStream("data.bin"));
int id = dataInputStream.readInt();
double value = dataInputStream.readDouble();
System.out.println("ID: " + id + ", Value: " + value);

In summary, choosing between Scanner and DataInputStream depends on the type of data you're working with. Scanner is best for human-readable data, while DataInputStream is ideal for binary data.

Related Articles