Java : System.console ()에서 입력을 얻는 방법


163

콘솔 클래스를 사용하여 사용자로부터 입력을 얻으려고하지만 호출 할 때 null 객체가 반환됩니다 System.console(). System.console을 사용하기 전에 변경해야합니까?

Console co=System.console();
System.out.println(co);
try{
    String s=co.readLine();
}

1
이것은 안드로이드입니까? (귀하의 사용자 ID로 추측합니다)
— Ryan Fernandes

프로그램을 시작하기 위해 이클립스를 사용하고 있습니까? java.exe를 사용하여 이클립스없이 프로그램을 시작하십시오.
— keuleJ

5
McDowell의 프로젝트 "AbstractingTheJavaConsole"을 살펴보십시오 : illegalargumentexception.googlecode.com/svn/trunk/code/java/…
— athspk

7
@RyanFernandes 그의 이름은 그의 질문과 어떻게 관련이 있습니까?
— b1nary.atr0phy

답변:


239

콘솔을 사용하여 입력 읽기 (IDE 외부에서만 사용 가능) :

System.out.print("Enter something:");
String input = System.console().readLine();

다른 방법 (모든 곳에서 작동) :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter String");
        String s = br.readLine();
        System.out.print("Enter Integer:");
        try {
            int i = Integer.parseInt(br.readLine());
        } catch(NumberFormatException nfe) {
            System.err.println("Invalid Format!");
        }
    }
}

IDE에서 System.console ()은 null을 반환합니다.
따라서 실제로 사용해야하는 경우 McDowellSystem.console() 에서이 솔루션을 읽으십시오 .


입력을 읽기 위해 BufferedReader가 필요한 이유 InputStreamReader에서 직접 읽을 수없는 이유
— Learner

2
답을 찾았습니다 : BufferedInputStream을 사용하면이 메서드는 오버로드 된 read () 메서드에 위임하여 8192 바이트의 바이트를 읽고 필요할 때까지 버퍼링합니다. 여전히 단일 바이트 만 반환하지만 다른 바이트는 예약 상태로 유지합니다. 이런 식으로 BufferedInputStream은 파일을 읽기 위해 OS에 대한 기본 호출을 줄입니다. 감사합니다
— Learner

사용자로부터 비밀번호를 읽으려면 stackoverflow.com/questions/22545603/… 는 별표로 줄을 숨 깁니다.
— oraclesoon

@Learner 또 다른 이유는 BufferedReader readLine()가 존재하지 않는 메소드 를 제공하기 때문일 수 있습니다 InputStreamReader.
— 마르코 노 1234

116
Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();

4
그러나 nextLine()작업하기가 매우 지저분합니다. 기껏해야 콘솔에서 전체 라인을 가져 오려고 할 때 두통이 발생합니다.
— Yokhen

9
@ Yokhen 문제를 일으킬 수있는 예를 들어 주 in.nextLine()시겠습니까?
— ajay

2
(1) 기본적으로 스캐너의 구분 기호는 공백이므로 사용자가 여러 텍스트를 입력하면 소프트웨어가 다음 몇 단계 ()로 진행하여 소프트웨어의 논리가 잘못됩니다. (2) nextLine ()을 사용하여 공백과 \ n \ r을 포함한 전체 문장을 읽으려면 사용자 입력을 trim ()해야합니다. (3) next ()는 사용자 입력을 기다리지 만 nextLine ()은 그렇지 않습니다. (4) useDelimiter ( "\\ r \\ n")를 테스트했지만 소프트웨어의 next () 논리가 다른 위치에서 다시 잘못됩니다. 결론적으로, 스캐너를 사용하여 사용자 입력을 읽는 것은 실제로 지저분합니다. BufferedReader가 최고입니다.
— oraclesoon

또한 스캐너에 문제가 있습니다. 특히 java.util.NoSuchElementException이해하지 못하는 것이 있습니다.
— Romain Vincent

이 모든 것은 try-with-resources 안에 있어야하며 줄을 읽으려면 메소드가 in.nextLine ()에 있어야합니다.
— 칼라 바신

35

콘솔 / 키보드에서 입력 문자열을 읽는 방법은 거의 없습니다. 다음 샘플 코드는 Java를 사용하여 콘솔 / 키보드에서 문자열을 읽는 방법을 보여줍니다.

public class ConsoleReadingDemo {

public static void main(String[] args) {

    // ====
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter user name : ");
    String username = null;
    try {
        username = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("You entered : " + username);

    // ===== In Java 5, Java.util,Scanner is used for this purpose.
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter user name : ");
    username = in.nextLine();      
    System.out.println("You entered : " + username);


    // ====== Java 6
    Console console = System.console();
    username = console.readLine("Please enter user name : ");   
    System.out.println("You entered : " + username);

}
}

사용 된 코드의 마지막 부분 java.io.Console 클래스를 . System.console()Eclipse를 통해 데모 코드를 실행할 때 콘솔 인스턴스를 가져올 수 없습니다 . Eclipse는 애플리케이션을 시스템 콘솔을 사용하는 최상위 프로세스가 아닌 백그라운드 프로세스로 실행하기 때문입니다.


18

환경에 따라 다릅니다. 당신이를 통해 스윙 UI 실행하는 경우 javaw예를 들어, 다음이 되지 않습니다 표시 할 콘솔 . IDE 내에서 실행중인 경우 특정 IDE의 콘솔 IO 처리에 크게 의존합니다.

명령 줄에서 괜찮을 것입니다. 견본:

import java.io.Console;

public class Test {

    public static void main(String[] args) throws Exception {
        Console console = System.console();
        if (console == null) {
            System.out.println("Unable to fetch console");
            return;
        }
        String line = console.readLine();
        console.printf("I saw this line: %s", line);
    }
}

다음과 java같이 실행하십시오 .

> javac Test.java
> java Test
Foo  <---- entered by the user
I saw this line: Foo    <---- program output

또 다른 옵션은 사용하는 것입니다 System.in당신이에 포장 할 수 있습니다, BufferedReader선, 또는 사용 읽기 Scanner(다시 포장을 System.in).


7

콘솔에서 읽는 것에 관한 좋은 대답을 찾았습니다. 또 다른 방법은 '스캐너'를 사용하여 콘솔에서 읽는 것입니다.

import java.util.Scanner;
String data;

Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();

scanInput.close();            
System.out.println(data);

1
close()이 경우 System.in을 닫고 나중에 응용 프로그램에서 읽지 못하게되므로 스캐너 를 호출하지 않을 수 있습니다 . (나중에 읽으면 "No line found"오류가 발생 함)
— Trevor

예, 프로그램에서 나중에 System.in을 사용하려는 경우 close ()를 사용해서는 안된다는 것에 동의합니다.
— akhouri

5

이 시도. 이것이 도움이되기를 바랍니다.

    String cls0;
    String cls1;

    Scanner in = new Scanner(System.in);  
    System.out.println("Enter a string");  
    cls0 = in.nextLine();  

    System.out.println("Enter a string");  
    cls1 = in.nextLine(); 

3

다음은 athspk의 답변을 취하여 사용자가 "종료"를 입력 할 때까지 계속 반복되는 답변 으로 만듭니다. 또한 이 코드를 가져 와서 테스트 할 수 있는 후속 답변을 작성 했습니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LoopingConsoleInputExample {

   public static final String EXIT_COMMAND = "exit";

   public static void main(final String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");

      while (true) {

         System.out.print("> ");
         String input = br.readLine();
         System.out.println(input);

         if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
            System.out.println("Exiting.");
            return;
         }

         System.out.println("...response goes here...");
      }
   }
}

출력 예 :

Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.

3

IDE 내에서 응용 프로그램을 실행할 때 System.console ()이 null 인 문제를 해결할 수 있는 Text-IO 라이브러리를 작성했습니다 .

McDowell이 제안한 것과 유사한 추상화 레이어를 소개합니다. . System.console ()이 null을 반환하면 라이브러리는 Swing 기반 콘솔로 전환됩니다.

또한 Text-IO에는 다음과 같은 유용한 기능이 있습니다.

  • 다양한 데이터 유형의 값 읽기를 지원합니다.
  • 민감한 데이터를 읽을 때 입력을 마스킹 할 수 있습니다.
  • 목록에서 값을 선택할 수 있습니다.
  • 입력 값에 대한 제약 조건 (형식 패턴, 값 범위, 길이 제약 조건 등)을 지정할 수 있습니다.

사용 예 :

TextIO textIO = TextIoFactory.getTextIO();

String user = textIO.newStringInputReader()
        .withDefaultValue("admin")
        .read("Username");

String password = textIO.newStringInputReader()
        .withMinLength(6)
        .withInputMasking(true)
        .read("Password");

int age = textIO.newIntInputReader()
        .withMinVal(13)
        .read("Age");

Month month = textIO.newEnumInputReader(Month.class)
        .read("What month were you born in?");

textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
        "was born in " + month + " and has the password " + password + ".");

에서 이 이미지 는 위의 코드는 스윙 기반 콘솔에서 실행 볼 수 있습니다.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.