java unix console

2015.07.05 20:27

졸리운_곰 조회 수:208

 

 

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

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
70 Cliche Command-Line Shell file 졸리운_곰 2015.07.12 726
69 Command Prompt Shell Interface in Java 졸리운_곰 2015.07.12 310
68 Eclipse RCP 프로그램에서 Console 뷰 사용하기 file 졸리운_곰 2015.07.08 410
67 I/O from the Command Line 졸리운_곰 2015.07.05 267
» java unix console 졸리운_곰 2015.07.05 208
65 java console 졸리운_곰 2015.07.05 223
64 Java Console and File Input/Output Cheat Sheet 졸리운_곰 2015.07.05 249
63 Demonstrates standard I/O redirection 졸리운_곰 2015.07.05 232
62 [SWING] 분석에 도전해볼만한 오픈소스 WebHarvest Java WebCrawler GUI file 졸리운_곰 2015.05.20 778
61 FreeLayout: A New Java Layout file 졸리운_곰 2015.05.14 315
60 JAVA SWT XML EDITOR sample : 자바 SWT XML 에디터 예제 file 졸리운_곰 2015.05.12 379
59 JAVA SWT 대화상자 예제 : 동적으로 컨트롤을 추가하고 삭제하는 예제 졸리운_곰 2015.05.11 345
58 JAVA SWT LINUX (Ubuntu) 에서 SWT Browser Control 사용시 졸리운_곰 2015.05.10 278
57 JAVA SWT TEST 자료 졸리운_곰 2015.05.07 752
56 SWT 스크롤 ScrolledComposite file 졸리운_곰 2015.05.03 407
55 xerces Xpath - search node from another node 졸리운_곰 2015.04.29 335
54 xerces를 사용한 dom 방식의 xml parser lib 졸리운_곰 2015.04.28 426
53 자바에서 XPath 사용 하기 졸리운_곰 2015.04.28 539
52 Java XML정리 : 노드선택 Select Node(s) 졸리운_곰 2015.04.28 442
51 SWT JAVA 동적으로 컨트롤을 추가하는 다이얼로그2 file 졸리운_곰 2015.04.27 325
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED