サーチ…


構文

  • スキャナスキャナ=新しいスキャナ(ソースソース);
  • スキャナスキャナ=新しいスキャナ(System.in);

パラメーター

パラメータ詳細
ソース Sourceは、String、Fileまたは任意の種類のInputStreamのいずれかです

備考

ScannerクラスはJava 5で導入されました。Java 6ではreset()メソッドが追加され、(新しい) Pathインターフェイスとの相互運用性のために、Java 7にはいくつかの新しいコンストラクタが追加されました。

Scannerを使用したシステム入力の読み取り

Scanner scanner = new Scanner(System.in); //Scanner obj to read System input
String inputTaken = new String();
while (true) {
    String input = scanner.nextLine(); // reading one line of input
    if (input.matches("\\s+"))         // if it matches spaces/tabs, stop reading
        break;
    inputTaken += input + " ";
}
System.out.println(inputTaken);

スキャナオブジェクトは、キーボードから入力を読み取るように初期化されます。 keyboarからの下の入力に対してはReading from keyboardとして出力を生成します

Reading
from
keyboard
  //space

Scannerを使用したファイル入力の読み取り

Scanner scanner = null;
try {
    scanner = new Scanner(new File("Names.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
} finally {
    if (scanner != null)
        scanner.close();
}

ここで、 Scannerオブジェクトは、テキストファイルの名前を含むFileオブジェクトを入力として渡すことによって作成されます。このテキストファイルはFileオブジェクトによって開かれ、スキャナオブジェクトによって次の行に読み込まれます。 scanner.hasNext()は、テキストファイルに次の行のデータがあるかどうかをチェックします。これをwhileループと組み合わせると、 Names.txtファイルのすべてのデータ行を繰り返しNames.txtできます。データそのものを取得するには、 nextLine()nextInt()nextBoolean()などのメソッドを使用できます。上記の例では、 scanner.nextLine()が使用されています。 nextLine()は、テキストファイル内の次の行を参照し、それをscannerオブジェクトと組み合わせることで、行の内容を出力することができます。スキャナオブジェクトを閉じるには、 .close()を使用します。

Java 7以降のリソースでtryを使って、上記のコードを以下のようにエレガントに書くことができます。

try (Scanner scanner = new Scanner(new File("Names.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (Exception e) {
    System.err.println("Exception occurred!");
}

Scannerを使用して入力全体を文字列として読み取る

Scannerを使用すると、 \Z (入力全体)を区切り文字として使用して、入力内のすべてのテキストを文字列として読み取ることができます。たとえば、これを使用して、テキストファイル内のすべてのテキストを1行で読み込むことができます。

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

Scannerを使用してファイルを読み込む例で説明しているように、Scannerを終了し、 IoExceptionがスローされる可能性があることにIoException

カスタム区切り文字の使用

.useDelimiter(",") 、Scannerでカスタム区切り文字(正規表現)を使用して、入力の読み込み方法を判断できます。これはString.split(...)と同様に機能しString.split(...) 。たとえば、 Scannerを使用して、文字列のコンマ区切り値のリストから読み込むことができます。

Scanner scanner = null;
try{
    scanner = new Scanner("i,like,unicorns").useDelimiter(",");;
    while(scanner.hasNext()){
        System.out.println(scanner.next());
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    if (scanner != null)
        scanner.close();
}

これにより、入力内のすべての要素を個別に読み取ることができます。あなたは、適切なCSVパーサライブラリを使用し、代わりに、CSVデータを解析するために、これを使用して見てはならないことに注意してくださいJava用のCSVパーサーを他の可能性のために。

タスクについて最もよく尋ねられる一般的なパターン

以下は、 java.util.Scannerクラスを適切に使用して、 System.inからのユーザー入力を対話的に正しく読み込む方法です( stdinとも呼ばれます。特にCやC ++、UnixやLinuxなどの言語でも使用されます)。これは、実行が要求されている最も一般的なことを慣用的に示しています。

package com.stackoverflow.scanner;

import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;

import static java.lang.String.format;

public class ScannerExample
{
    private static final Set<String> EXIT_COMMANDS;
    private static final Set<String> HELP_COMMANDS;
    private static final Pattern DATE_PATTERN;
    private static final String HELP_MESSAGE;

    static
    {
        final SortedSet<String> ecmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        ecmds.addAll(Arrays.asList("exit", "done", "quit", "end", "fino"));
        EXIT_COMMANDS = Collections.unmodifiableSortedSet(ecmds);
        final SortedSet<String> hcmds = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        hcmds.addAll(Arrays.asList("help", "helpi", "?"));
        HELP_COMMANDS = Collections.unmodifiableSet(hcmds);
        DATE_PATTERN = Pattern.compile("\\d{4}([-\\/])\\d{2}\\1\\d{2}"); // http://regex101.com/r/xB8dR3/1
        HELP_MESSAGE = format("Please enter some data or enter one of the following commands to exit %s", EXIT_COMMANDS);
    }

    /**
     * Using exceptions to control execution flow is always bad.
     * That is why this is encapsulated in a method, this is done this
     * way specifically so as not to introduce any external libraries
     * so that this is a completely self contained example.
     * @param s possible url
     * @return true if s represents a valid url, false otherwise
     */
    private static boolean isValidURL(@Nonnull final String s)
    {
        try { new URL(s); return true; }
        catch (final MalformedURLException e) { return false; }
    }

    private static void output(@Nonnull final String format, @Nonnull final Object... args)
    {
        System.out.println(format(format, args));
    }

    public static void main(final String[] args)
    {
        final Scanner sis = new Scanner(System.in);
        output(HELP_MESSAGE);
        while (sis.hasNext())
        {
            if (sis.hasNextInt())
            {
                final int next = sis.nextInt();
                output("You entered an Integer = %d", next);
            }
            else if (sis.hasNextLong())
            {
                final long next = sis.nextLong();
                output("You entered a Long = %d", next);
            }
            else if (sis.hasNextDouble())
            {
                final double next = sis.nextDouble();
                output("You entered a Double = %f", next);
            }
            else if (sis.hasNext("\\d+"))
            {
                final BigInteger next = sis.nextBigInteger();
                output("You entered a BigInteger = %s", next);
            }
            else if (sis.hasNextBoolean())
            {
                final boolean next = sis.nextBoolean();
                output("You entered a Boolean representation = %s", next);
            }
            else if (sis.hasNext(DATE_PATTERN))
            {
                final String next = sis.next(DATE_PATTERN);
                output("You entered a Date representation = %s", next);
            }
            else // unclassified
            {
                final String next = sis.next();
                if (isValidURL(next))
                {
                    output("You entered a valid URL = %s", next);
                }
                else
                {
                    if (EXIT_COMMANDS.contains(next))
                    {
                        output("Exit command %s issued, exiting!", next);
                        break;
                    }
                    else if (HELP_COMMANDS.contains(next)) { output(HELP_MESSAGE); }
                    else { output("You entered an unclassified String = %s", next); }
                }
            }
        }
        /*
           This will close the underlying Readable, in this case System.in, and free those resources.
           You will not be to read from System.in anymore after this you call .close().
           If you wanted to use System.in for something else, then don't close the Scanner.
        */
        sis.close();
        System.exit(0);
    }
}

コマンドラインからintを読み込む

import java.util.Scanner;

Scanner s = new Scanner(System.in);
int number = s.nextInt();

コマンドラインからintを読みたい場合は、このスニペットを使用してください。まず、コマンドラインからプログラムを起動すると、デフォルトではコマンドラインであるSystem.inをリッスンするScannerオブジェクトを作成する必要があります。その後、Scannerオブジェクトの助けを借りて、ユーザーがコマンドラインに渡した最初のintを読み取って変数番号に格納します。これで、保存されたintを使って、何でもできます。

慎重にスキャナを閉じる

コンストラクタのパラメータとしてSystem.inを指定したスキャナを使用すると、スキャナを閉じるとInputStreamも閉じてしまうことに気づく必要があります。スキャナオブジェクト)は、 java.util.NoSuchElementExceptionまたはjava.lang.IllegalStateExceptionをスローしjava.lang.IllegalStateException

例:

    Scanner sc1 = new Scanner(System.in);
    Scanner sc2 = new Scanner(System.in);
    int x1 = sc1.nextInt();
    sc1.close();
    // java.util.NoSuchElementException
    int x2 = sc2.nextInt();
    // java.lang.IllegalStateException
    x2 = sc1.nextInt();


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow