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”.