java unix console

2015.07.05 20:27

졸리운_곰 조회 수:214

 

 

Console input
The Console class allows the user to interact with a simple console application, using textual commands that you define.

Here's a simple example of its use:

 
import java.util.Arrays;
import java.io.Console;

/**
* Simple interactive console application.
* Uses the java.io.Console class of Java 6.
*/
public final class Console6 {

  public static final void main(String... aArgs){
    Console console = System.console();
    //read user name, using java.util.Formatter syntax :
    String username = console.readLine("User Name? ");

    //read the password, without echoing the output 
    char[] password = console.readPassword("Password? ");

    //verify user name and password using some mechanism (elided)

    //the javadoc for the Console class recommends "zeroing-out" the password 
    //when finished verifying it :
    Arrays.fill(password, ' ');

    console.printf("Welcome, %1$s.", username);
    console.printf(fNEW_LINE);

    String className = console.readLine("Please enter a package-qualified class name:");
    Class theClass = null;
    try {
      theClass = Class.forName(className);
      console.printf("The inheritance tree: %1$s", getInheritanceTree(theClass));
    }
    catch(ClassNotFoundException ex){
      console.printf("Cannot find that class.");
    }

    //this version just exits, without asking the user for more input
    console.printf("Bye.");
  }
  
  // PRIVATE
  private static final String fNEW_LINE = System.getProperty("line.separator");

  private static String getInheritanceTree(Class aClass){
    StringBuilder superclasses = new StringBuilder();
    superclasses.append(fNEW_LINE);
    Class theClass = aClass;
    while (theClass != null) {
      superclasses.append(theClass);
      superclasses.append(fNEW_LINE);
      theClass = theClass.getSuperclass();
    }
    superclasses.append(fNEW_LINE);
    return superclasses.toString();
  }
} 
 

An example run:

>java  Console6
User Name? john
Password?
Welcome, john.
Please enter a package-qualified class name:java.util.ArrayList
The inheritance tree:
class java.util.ArrayList
class java.util.AbstractList
class java.util.AbstractCollection
class java.lang.Object

Bye.

JDK < 6

The Console class was added in Java 6. The following is an extended example of using an older version of the JDK. Here, input is read from the console in a continuous loop. As well, it has separated the problem into several parts, such that some parts can be reused in other console applications.

As in the previous example, the user inputs a package-qualified class name, and the corresponding inheritance tree is displayed.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

An example run:

>java -cp . Console InheritanceInterpreter
Please enter a class name>as;k
Invalid.  Example:"java.lang.String">java.lang.String
The inheritance tree:
class java.lang.String
class java.lang.Object
Please enter a class name>
Invalid.  Example:"java.lang.String">
Invalid.  Example:"java.lang.String">....
Invalid.  Example:"java.lang.String">a;lskf
Invalid.  Example:"java.lang.String">java.sql.SQLWarning
The inheritance tree:
class java.sql.SQLWarning
class java.sql.SQLException
class java.lang.Exception
class java.lang.Throwable
class java.lang.Object
Please enter a class name>java.util.GregorianCalendar
The inheritance tree:
class java.util.GregorianCalendar
class java.util.Calendar
class java.lang.Object
Please enter a class name>exit

Bye.

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
* Sends text back and forth between the command line and an
* Interpreter. JDK less than 6.
*/
public final class Console {

  /**
  * Build and launch a specific <code>Interpreter</code>, whose
  * package-qualified name is passed in on the command line.
  */
  public static void main(String... aArguments) {
    try {
      Class theClass = Class.forName(aArguments[0]);
      Interpreter interpreter = (Interpreter)theClass.newInstance();
      Console console = new Console(interpreter);
      console.run();
    }
    catch (ClassNotFoundException ex){
      System.err.println(ex + " Interpreter class must be in class path.");
    }
    catch(InstantiationException ex){
      System.err.println(ex + " Interpreter class must be concrete.");
    }
    catch(IllegalAccessException ex){
      System.err.println(ex + " Interpreter class must have a no-arg constructor.");
    }
  }

  public Console(Interpreter aInterpreter) {
    if (aInterpreter == null) {
      throw new IllegalArgumentException("Cannot be null.");
    }
    fInterpreter = aInterpreter;
  }

  /**
  * Display a prompt, wait for a full line of input, and then parse
  * the input using an Interpreter.
  *
  * Exit when <code>Interpreter.parseInput</code> returns true.
  */
  public void run() {
    display(fInterpreter.getHelloPrompt());

    //pass each line of input to fInterpreter, and display
    //fInterpreter's result
    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    BufferedReader stdin = new BufferedReader(inputStreamReader);
    boolean hasRequestedQuit = false;
    String line = null;
    List<Object> result = new ArrayList<Object>();
    try {
      while(!hasRequestedQuit){
        line = stdin.readLine();
        //note that "result" is passed as an "out" parameter
        hasRequestedQuit = fInterpreter.parseInput(line, result);
        display(result);
        result.clear();
      }
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
    finally {
      display(fBYE);
      shutdown(stdin);
    }
  }

  // PRIVATE
  private static final String fBYE = "Bye.";
  private Interpreter fInterpreter;

  /**
  * Display some text to stdout.
  * The result of toString() is used.
  */
  private void display(Object aText){
    System.out.print(aText.toString());
    System.out.flush();
  }

  /**
  * Display a List of objects as text in stdout, in the order returned
  * by the iterator of aText.
  */
  private void display(List<Object> aText) {
    for(Object item : aText){
      display(item);
    }
  }

  private void shutdown(Reader aStdin){
    try {
      aStdin.close();
    }
    catch (IOException ex){
      System.err.println(ex);
    }
  }
} 
 
import java.util.*;

/**
* Parse a line of text and return a result.
*/
public interface Interpreter {

  /**
  * @param aLine is non-null.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of items which all have a <code>toString</code> method, to be used
  * for displaying a result to the user.
  *
  * @return true if the user has requested to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  boolean parseInput(String aLine, List<Object> aResult);

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  String getHelloPrompt();
} 
 
import java.util.*;

/**
* Given a package-qualified class name, return the names of the classes in
* the inheritance tree.
*/
public final class InheritanceInterpreter implements Interpreter {

  /**
  * @param aLine is a non-null name of a class.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of class names which form the inheritance tree of the input class.
  *
  * @return true if the user has requeseted to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  public boolean parseInput (String  aLine, final List aResult) {
    if (aResult == null) {
      throw new IllegalArgumentException("Result param cannot be null.");
    }
    if (!aResult.isEmpty()){
      throw new IllegalArgumentException("Result param must be empty.");
    }
    if (aLine == null) {
      throw new IllegalArgumentException("Line must not be null.");
    }

    boolean hasRequestedQuit = aLine.trim().equalsIgnoreCase(fQUIT) ||
                               aLine.trim().equalsIgnoreCase(fEXIT);
    if (hasRequestedQuit) {
      aResult.add(fNEW_LINE);
    }
    else {
      try {
        Class theClass = Class.forName(aLine);
        StringBuilder superclasses = new StringBuilder();
        superclasses.append(fHEADER);
        superclasses.append(fNEW_LINE);
        while (theClass != null) {
          superclasses.append(theClass);
          superclasses.append(fNEW_LINE);
          theClass = theClass.getSuperclass();
        }
        aResult.add(superclasses);
        aResult.add(fDEFAULT_PROMPT);
      }
      catch (ClassNotFoundException ex){
        //recover by asking the user for corrected input
        aResult.clear();
        aResult.add(fERROR_PROMPT);
      }
    }

    assert !aResult.isEmpty(): "Result must be non-empty.";

    return hasRequestedQuit;
  }

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  public String getHelloPrompt() {
    return fHELLO_PROMPT;
  }

  // PRIVATE
  private static final String fHELLO_PROMPT = "Please enter a class name>";
  private static final String fDEFAULT_PROMPT = "Please enter a class name>";
  private static final String fERROR_PROMPT = "Invalid.  Example:\"java.lang.String\">";
  private static final String fHEADER = "The inheritance tree:";
  private static final String fQUIT = "quit";
  private static final String fEXIT = "exit";
  private static final String fNEW_LINE = System.getProperty("line.separator");
} 

 

[출처] http://www.javapractices.com/topic/TopicAction.do?Id=79

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
22 Command Prompt Shell Interface in Java 졸리운_곰 2015.07.12 310
21 java console 졸리운_곰 2015.07.05 223
20 Java Console and File Input/Output Cheat Sheet 졸리운_곰 2015.07.05 249
19 Demonstrates standard I/O redirection 졸리운_곰 2015.07.05 232
18 Java로 외부 프로그램 실행 ( ProcessBuilder 사용) 졸리운_곰 2015.03.17 1175
17 Java Clipboard 자바 클립보드 복사/붙여넣기 졸리운_곰 2015.03.17 2214
16 Java Inner class 자바 중첩(내부)클래스 졸리운_곰 2015.03.03 887
15 IzPack으로 GUI 설치 프로그램 만들기 file 졸리운_곰 2015.02.15 638
14 [Java],[AWT],[Layout],[AWT Layout], file 졸리운_곰 2015.02.13 375
13 [Java],[AWT],[SWING], Java GUI file 졸리운_곰 2015.02.13 923
12 [Java][AWT 개요] file 졸리운_곰 2015.02.13 464
11 javac 로 컴파일 시 유니코드(utf-8) 한글 소스 코드 컴파일 문제 졸리운_곰 2015.02.02 1135
10 파일 존재 여부 판단, 디렉토리 있는지 확인 함수; File Directory Exist 졸리운_곰 2014.03.03 1215
9 Java Static 변수 졸리운_곰 2014.01.28 1102
8 Properties 클래스 사용하기. 졸리운_곰 2014.01.28 1027
7 Java => Thread 졸리운_곰 2014.01.28 836
6 Java 세마포어(Semaphore) 가을의 곰을... 2013.12.11 2517
5 Java Thread 제어 (Thread Pool) 가을의 곰을... 2013.12.11 976
4 Java Delay (지연실행) 루틴 가을의 곰을... 2013.11.20 1364
3 Java Runtime시 Memory monitoring 가을의 곰을... 2013.11.19 875
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED