Java User Input & Files

Scanner and reading/writing files.

✍️ 2 exercises in this lesson

User input

Scanner reads input from the keyboard:

Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = sc.nextInt();

Files

The modern java.nio.file.Files class makes file work simple:

  • Files.writeString(path, text)
  • Files.readString(path) / Files.readAllLines(path)
  • Files.exists(path), Files.delete(path)

Key Takeaways: Java User Input & Files

Mastering Java User Input & Files helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java User Input & Files Code Example

Java
import java.nio.file.*;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("notes.txt");
        Files.writeString(file, "Learn Java\nBuild apps\n");

        for (String line : Files.readAllLines(file)) {
            System.out.println("> " + line);
        }
        Files.delete(file);

        Scanner sc = new Scanner(System.in);
        System.out.print("Your name: ");
        String name = sc.nextLine();
        System.out.println("Welcome, " + name + "!");
    }
}
Output
> Learn Java
> Build apps
Your name: Hina
Welcome, Hina!
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java User Input & Files Practice Exercises

Check what you learned in “Java User Input & Files”.

/ 2 solved
Fill in the blank

Read input from the keyboard.

Scanner sc = new (System.in);
✓ Correct! Not quite. Try again.
Multiple choice

Which class has readString() and writeString()?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services