Java 中的标准输入/输出如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37224120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:18:35  来源:igfitidea点击:

How does StdIn/Out in Java work?

javastdoutstdin

提问by augusti

Im new to Java and am trying to make a QuickUnion algorithm run. I have these text files on my desktop and want to program to read the integers in them. This is the end of the QuickUnion class.

我是 Java 新手,正在尝试运行 QuickUnion 算法。我的桌面上有这些文本文件,并希望通过编程来读取其中的整数。这是 QuickUnion 类的结束。

 public static void main(String[] args) {

    int N = StdIn.readInt();    // Read number of sites
    QuickUnionUF quickunion = new QuickUnionUF(N);
    while (!StdIn.isEmpty()) {
        int p = StdIn.readInt();
        int q = StdIn.readInt();                     // Read pair to connect
        if (quickunion.connected(p, q)) continue;     // Ignore if connected
        quickunion.union(p, q);                       // Combine components
        StdOut.println(p + " " + q);                 // and print connection
    }
    StdOut.println(quickunion.count() + " components");
}

My question is: how does StdIn work? How do I read the text file? the first test file contains two columns of numbers.

我的问题是:StdIn 是如何工作的?如何读取文本文件?第一个测试文件包含两列数字。

回答by Stephen C

The Stdlibrary 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.

Std库不提供从任意文件读取所需的功能。它的目的是为初学者(学生)提供一种简单的方法来编写简单的程序来读写标准输入/标准输出。它的功能有限1

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

相比之下,生产代码直接或(在 的情况下)通过类使用标准System.inand 。因此,要从生产代码中的文件(或标准输入)中读取文本,您通常会执行以下操作:System.outSystem.inScanner

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

or

或者

Scanner in = new Scanner(System.in);

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

然后使用各种Scanner方法读取行或单个项目。

(You could also use the Readeror BufferedReaderAPIs, 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.)

(您也可以使用ReaderBufferedReaderAPI,并以各种方式自己解析输入行。或者使用现有的解析器库来读取 CSV 文件、JSON 文件、XML 文件等。)

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 FileNotFoundExceptionwhich your code must deal with.

请注意,new Scanner(new File(someString))声明为抛出FileNotFoundException您的代码必须处理。



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

1 - 我的建议是停止使用StdInStdOut其余的尽快。学习使用标准 API 并切换。

回答by blueFalcon

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

标准库 (Std) 通常是为参加 Java 编程第一门课程的学生提供的。Std 库不是“已安装的 Java 库”的一部分,因此为了使用它,您必须下载 Std 库并在您的路径中声明它。它的工作原理与 Java Scanner 类相同。考虑

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

它只接收一个整数a,并将其打印出来。正如我所看到的isEmpty(),如果标准输入为空(空格可能除外),则您正在使用which 返回 true 。因此,您可以使用 接收任意数量的isEmpty()输入。这是此用法的示例代码

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.

它会立即计算您输入的平均值并在您输入新输入时将其打印出来。