The Std library does not provide the functionality that is needed to read from an arbitrary file. Its purpose is to provide an easy way for beginners (students) to write simple programs that read and write to standard input / standard output. It has limited functionality1.

By contrast, production code uses the standard System.in and System.out, either directly or (in the case of System.in) via the Scanner class. So to read text from a file (or standard input) in production code, you would typically do something like this:

Scanner in = new Scanner(new File("/some/path/to/file.txt"));

or

Scanner in = new Scanner(System.in);

and then use the various Scanner methods to either read lines or individual items.

(You could also use the Reader or BufferedReader APIs, and parse the input lines yourself in various ways. Or use an existing parser library to read CSV files, JSON files, XML files and so on.)

Your example would look something like this:

import java.util.Scanner;
...
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);  // replace as required!
    int n = in.nextInt();    // Read number of sites
    QuickUnionUF quickUnion = new QuickUnionUF(n);
    while (in.hasNextInt()) {
        int p = in.nextInt();
        int q = in.nextInt();                     // Read pair to connect
        if (quickUnion.connected(p, q)) continue; // Ignore if connected
        quickUnion.union(p, q);                   // Combine components
        System.out.println(p + " " + q);          // and print connection
    }
    System.out.println(quickUnion.count() + " components");
}

Note that new Scanner(new File(someString)) is declared as throwing FileNotFoundException which your code must deal with.


1 - My advice would be to stop using StdIn, StdOut and the rest as soon as you can. Learn to use the standard APIs, and switch.

Answer from Stephen C on Stack Overflow
🌐
Princeton CS
introcs.cs.princeton.edu › java › stdlib › javadoc › StdIn.html
StdIn
As an example, the following code fragment reads all of the remaining tokens from standard input and returns them as an array of strings. ... Differences with Scanner. StdIn and Scanner are both designed to parse tokens and convert them to primitive types and strings.
🌐
Princeton CS
introcs.cs.princeton.edu › java › stdlib › StdIn.java.html
StdIn.java
January 18, 2024 - * @return all remaining doubles on standard input, as an array * @throws InputMismatchException if any token cannot be parsed as a {@code double} */ public static double[] readAllDoubles() { String[] fields = readAllStrings(); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } //// end: section (2 of 2) of code duplicated from In to StdIn // do this once when StdIn is initialized static { resync(); } /** * If StdIn changes, use this to reinitialize the scanner. */ private static void resync() { setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME)); } private static void setScanner(Scanner scanner) { StdIn.scanner = scanner; StdIn.scanner.useLocale(LOCALE); } /** * Reads all remaining tokens, parses them as integers, and returns * them as an array of integers.
🌐
HackerRank
hackerrank.com › challenges › java-stdin-and-stdout-1 › problem
Java Stdin and Stdout I | HackerRank
For example: Scanner scanner = new Scanner(System.in); String myString = scanner.next(); int myInt = scanner.nextInt(); scanner.close(); System.out.println("myString is: " + myString); System.out.println("myInt is: " + myInt); The code above ...
Top answer
1 of 2
3

The Std library does not provide the functionality that is needed to read from an arbitrary file. Its purpose is to provide an easy way for beginners (students) to write simple programs that read and write to standard input / standard output. It has limited functionality1.

By contrast, production code uses the standard System.in and System.out, either directly or (in the case of System.in) via the Scanner class. So to read text from a file (or standard input) in production code, you would typically do something like this:

Scanner in = new Scanner(new File("/some/path/to/file.txt"));

or

Scanner in = new Scanner(System.in);

and then use the various Scanner methods to either read lines or individual items.

(You could also use the Reader or BufferedReader APIs, and parse the input lines yourself in various ways. Or use an existing parser library to read CSV files, JSON files, XML files and so on.)

Your example would look something like this:

import java.util.Scanner;
...
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);  // replace as required!
    int n = in.nextInt();    // Read number of sites
    QuickUnionUF quickUnion = new QuickUnionUF(n);
    while (in.hasNextInt()) {
        int p = in.nextInt();
        int q = in.nextInt();                     // Read pair to connect
        if (quickUnion.connected(p, q)) continue; // Ignore if connected
        quickUnion.union(p, q);                   // Combine components
        System.out.println(p + " " + q);          // and print connection
    }
    System.out.println(quickUnion.count() + " components");
}

Note that new Scanner(new File(someString)) is declared as throwing FileNotFoundException which your code must deal with.


1 - My advice would be to stop using StdIn, StdOut and the rest as soon as you can. Learn to use the standard APIs, and switch.

2 of 2
1

Standard library (Std) is often provided for students who are taking their first course in programming in Java. Std library is not part of "installed java libraries" therefore in order to use it you have to download the Std library and declare it in your path. It works identical to Java Scanner class. Consider

public static void main(String[] args) {
        StdOut.print("Type an int: ");
        int a = StdIn.readInt();
        StdOut.println("Your int was: " + a);
        StdOut.println();
    }
}

Which takes in only ONE integer, a , and prints it out. How ever as I see you're using isEmpty()which returns true if standard input is empty (except possibly for whitespace). Therefore you can use the isEmpty() to take in as many input as you want. Here is an example code of this usage

public static void main(String[] args) {
        double sum = 0.0; // cumulative total
        int n = 0; // number of values
        while (!StdIn.isEmpty()) {
            double x = StdIn.readDouble();
            sum = sum + x;
            n++;
        }
        StdOut.println(sum / n);
}

Which calculates instantly the average of your inputs and prints it out as you type in new input.

🌐
Code Example
kodingbeta.wordpress.com › 2018 › 11 › 26 › java-stdin-and-stdout
Java Stdin and Stdout - Code Example - WordPress.com
December 7, 2018 - Instruksi : In this challenge, you must read an integer, a double, and a String from stdin, then print the values according to the instructions in the Output Format section below. To make the probl…
🌐
Linux Hint
linuxhint.com › read-input-through-stdin-java
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Study.com
study.com › computer science courses › computer science 109: introduction to programming
Standard Input Methods in Java - Lesson | Study.com
December 6, 2023 - We therefore use System.in to specify that we want to read from 'stdin' (to accept input from the console). There are a number of classes that we can then use for the actual reading and processing of the data. The two most commonly used are Scanner and BufferedReader. To unlock this lesson you must be a Study.com member Create an account · The Scanner class (package java.util.Scanner) is a text scanner that breaks up input into tokens based on a delimiter pattern such as space (default), semi-colon, tab, etc.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-read-from-standard-input-in-java
How can we read from standard input in Java?
May 29, 2025 - The standard input (stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings.
Find elsewhere
🌐
EnableGeek
enablegeek.com › home › stdin java : input methods in java explained
Stdin JAVA : Input Methods in Java Explained - EnableGeek
April 2, 2024 - In this article, we will discuss how to handle multiple inputs using stdin in Java programs. ... When we need to read multiple inputs of the same data type, we can use loops and arrays to simplify the input handling process. For example, if we need to read n integers from stdin, we can use ...
🌐
Medium
cdbutle.medium.com › java-stdin-and-stdout-a20edf2eedfe
Java Stdin and Stdout. Continuing our journey down the Java… | by Charles Butler Jr | Medium
September 3, 2021 - Continuing our journey down the Java rabbit hole we land on a new principle in the code base. That of reading input. In Java most challenges we’ll face have us reading input from stdin (aka standard input) and somehow manipulating that data to output to stdout.
🌐
OneCompiler
onecompiler.com › java › 3x42gkk3g
stdin - Java - OneCompiler
Following is a sample program that ... case ). import java.util.Scanner; class Input { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your name: "); String inp = input.next(); System.out.println("Hello, " + inp); } }...
🌐
InterviewBit
interviewbit.com › problems › stdin-and-stdout
Stdin and Stdout | InterviewBit
One popular way to read input from ... the Input Stream as System.in. For example: Scanner scanner = new Scanner(System.in); String userString = scanner.next(); int userInt = ......
🌐
CliffsNotes
cliffsnotes.com › home › computer science
Utilize Java StdIn Methods for Input in Programs - CliffsNotes
March 13, 2026 - /* while ( !StdIn.isEmpty() ) { // in order to break the loop, StdIn.isEmpty = true, you press CTRL+D int val = StdIn.readInt(); System.out.println("Entered Value: " + val); } System.out.println("End of inputs :("); // the program will run the WHILE LOOP until we aignal it to stop, which allows for this message to display */ // (6.1j) Redirect standard output to a file when executing a program. /* // Lets do an example where we get a bunch of lines printed // guess a number between 1 and 10 int secret = 1 + (int) (Math.random() * 10); // the Math.random gives from 0.99 , which gets rounded to
🌐
UW Computer Sciences
pages.cs.wisc.edu › ~mcw › cs367 › programs › P4 › notes › io.html
I/O in Java
The System class also gives us a stream for reading input from the user. This stream is called System.in and is often referred to as "standard in" (stdin). System.in is an instance of the InputStreamClass.
🌐
University at Buffalo
cse.buffalo.edu › jive › compaction › Trie › StdIn.java
StdIn.java
* @return all remaining doubles on standard input, as an array * @throws InputMismatchException if any token cannot be parsed as a double */ public static double[] readAllDoubles() { String[] fields = readAllStrings(); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /*** end: section (2 of 2) of code duplicated from In to StdIn */ // do this once when StdIn is initialized static { resync(); } /** * If StdIn changes, use this to reinitialize the scanner. */ private static void resync() { setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME)); } private static void setScanner(Scanner scanner) { StdIn.scanner = scanner; StdIn.scanner.useLocale(LOCALE); } /** * Reads all remaining tokens, parses them as integers, and returns * them as an array of integers.
🌐
GitHub
github.com › RyanFehr › HackerRank › blob › master › Java › Java Stdin and Stdout I › Solution.java
HackerRank/Java/Java Stdin and Stdout I/Solution.java at master · RyanFehr/HackerRank
//In this challenge, you must read integers from stdin and then print them to stdout. Each integer must be printed on a new line. To make the problem a little easier, a portion of the code is provided for you in the editor below. · // · //Input Format · // · //There are three lines of input, and each line contains a single integer. · // · //Sample Input · // · //42 · //100 · //125 · //Sample Output · // · //42 · //100 · //125 · · · import java.util.*; ·
Author   RyanFehr
🌐
Blogger
javaispapa.blogspot.com › 2017 › 07 › java-stdin-and-stdout.html
Java Tutorial: Java Stdin and Stdout
August 29, 2017 - 2 . Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output). ...
🌐
LabEx
labex.io › tutorials › java-how-to-read-stdin-in-java-502562
How to read stdin in Java | LabEx
This tutorial explores various techniques for reading standard input in Java, providing developers with comprehensive strategies to handle console input effectively. Java offers multiple approaches to stdin processing, enabling programmers to choose the most suitable method for their specific ...
🌐
Emory University
cs.emory.edu › ~cs323000 › book › StdIn.java
StdIn.java
* For additional documentation, see Section 1.5 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class StdIn { // assume Unicode UTF-8 encoding private static String charsetName = "UTF-8"; // assume language = English, country = US for consistency with System.out.