Using Scanner in Java to Create and Read a Text File

This document explains how to use the Scanner class in Java to create a text file, write data into it, and then read that data back.

Objective

This lesson will show you how to:

  1. Create a text file in Java.
  2. Write data into it (from scanner input).
  3. Read that data back from the same file and print it out.

Step 1: Import the Required Classes

This explains the imports.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

Step 2: Create a Text File and Write Data

Click here and copy my source code into your Eclipse.
The name of the file will be: PX_CreateFileHardCoded_lastname

Files to Submit (Google Classroom)

This is the location of your file when the execute the program above


Step 3: Read Data Back from the File and Print It

Click here and copy my source code into your Eclipse.
The name of the file will be: PX_ReadOneLine_lastname

Files to Submit (Google Classroom)

💡 This program uses Scanner again, but this time to read lines from the file and display them in the console.

Summary

  1. Create the input.dat file with hardcoded data.
  2. Read the file input.dat again using Scanner.