> Java > java지도 시간 > 본문

자바 콘솔

PHPz
풀어 주다: 2024-08-30 16:10:15
원래의
351명이 탐색했습니다.

Java 콘솔은 문자 기반 항목을 읽는 콘솔 장치를 실행하기 위해 JDK 1.6에 도입된 java.io 패키지에 있는 클래스입니다. 이 클래스는 사용자의 입력을 읽고 이를 콘솔에 다시 쓰는 데 사용됩니다. 이는 아래 2가지 이유 때문에 버퍼링된 리더 및 라이터보다 선호됩니다.-

  1. System 클래스를 사용하여 새 Console 인스턴스를 호출하고 Console 클래스에는 자체 생성자가 없으므로 액세스하기 쉽습니다.
  2. 화면에 표시되지 않는 비밀번호 등 보안정보를 입력하는 데 도움이 됩니다.

구문:

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

public final class Console extends Object implements Flushable
로그인 후 복사

Java에서 콘솔 클래스는 어떻게 작동하나요?

Console 클래스는 콘솔에서 입력을 읽거나 콘솔에 출력을 쓰는 데 사용됩니다. Console 클래스에는 생성자가 없고 System 클래스를 사용하여 인스턴스화되므로 사용하기가 더 쉽습니다. 또한 Console 클래스는 사용자가 보안 자격 증명과 같은 입력을 화면에 표시되지 않도록 도와주기 때문에 보다 안전한 방식으로 콘솔의 입력을 읽습니다. 따라서 콘솔 클래스는 보안 자격 증명으로 작업해야 하는 경우 매우 유용합니다.

Java 콘솔의 방법

Java Console의 메소드는 다음과 같습니다.

1. public PrintWriterwriter(): 이 메서드는 실행 중인 콘솔 개체와 연결된 PrintWriter의 고유 인스턴스를 검색하는 데 사용됩니다. 이 방법에는 매개변수가 필요하지 않습니다.

2. public void flash(): Console 클래스는 콘솔 인스턴스를 플러시하기 위해 이 메소드를 제공합니다. 또한 버퍼에 출력이 있는 경우 즉시 출력을 인쇄하도록 주의를 기울입니다. 이 함수를 호출하는 데에는 매개변수가 필요하지 않습니다.

3. public Reader reader(): 이 메서드는 현재 콘솔과 연결된 Reader 클래스의 고유한 인스턴스를 제공합니다. Reader 클래스의 인스턴스는 콘솔에서 문자를 읽기 위한 입력으로 제공됩니다.

4. 공개 콘솔 형식( StringformatVar, Object … age): 이 메서드는 지정된 형식 문자열과 인수를 사용하여 콘솔 출력 스트림에 지정된 형식 문자열을 보내는 데 도움이 됩니다.

매개변수:

  • formatVar: 형식 문자열은 지정된 문자열과 인수를 사용하여 콘솔 출력에 인쇄되어야 합니다.
  • args: 이러한 인수는 formatVar에 전달된 문자열의 형식 지정자에 의해 참조됩니다.

콘솔 인스턴스는 형식화된 문자열이 인쇄된 이 함수의 출력으로 전송됩니다. 이 메소드는 지정된 형식에 올바른 구문이 없는 경우 IllegalFormatException을 발생시킵니다.

5. public Console printf( StringformatVar, Object … agrs): 이 메소드는 콘솔 화면에 전달된 지정된 형식 인수를 사용하여 형식화된 문자열을 인쇄하는 데 도움이 됩니다.

  • formatVar – 형식 문자열은 지정된 문자열과 인수를 사용하여 콘솔 출력에 인쇄되어야 합니다.
  • args – 이러한 인수는 formatVar에 전달된 문자열의 형식 지정자에 의해 참조됩니다.

콘솔 인스턴스는 형식화된 문자열이 인쇄된 이 함수의 출력으로 전송됩니다. 이 메소드는 지정된 형식에 올바른 구문이 없는 경우 IllegalFormatException을 발생시킵니다.

6. public String readLine( StringformatVar, Object … age): 이 메소드는 화면에 형식화된 프롬프트를 표시하는 데 사용되며 사용자가 입력한 한 줄을 읽습니다.

줄 끝 문자를 제외하고 콘솔의 프롬프트에서 읽은 단일 줄이 메서드에 의해 반환됩니다. 아무것도 입력하지 않은 경우 이 메서드는 null을 반환합니다. 이 메소드는 지정된 형식에 올바른 구문이 없는 경우 IllegalFormatException을 발생시킵니다. 또한 I/O 오류가 발생하면 IOError가 발생합니다.

7. public String readLine(): 이 메소드는 콘솔에서 사용자가 입력한 한 줄을 읽는 데 사용되며, 전달된 경우 이스케이프 문자는 제외됩니다.

이 문자열은 메소드에 의해 반환되거나 줄 끝에 도달한 경우 null이 반환됩니다. 프롬프트가 표시되지 않으므로 이 방법에는 매개변수가 필요하지 않습니다. 이 방법을 사용하는 동안 모든 I/O 오류에 대해 IOERROR가 발생합니다.

8. public char[] readPassword( String formatVar, Object … age): 이 메소드는 보안 모드를 사용하여 문자를 읽는 형식화된 프롬프트를 화면에 표시하지 않도록 화면에 표시하는 데 사용됩니다.

  • formatVar: The format string needs to be printed on the console output using the specified string and arguments.
  • args: These arguments are referred to by the format specifiers in the string passed in formatVar.

Character Array containing the password is sent as output by this function or null in case the end-of-line is reached. The returned character array excludes line-termination characters. This method throws IllegalFormatException in case the format specified does not have the correct syntax. This method IOERROR occurs for any I/O errors.

9. public char[] readPassword(): This method is used to read password string from the console in a secure mode without displaying any prompt. There are no parameters that need to be passed. The string of characters containing the password is returned excluding the line-termination characters or null in case the end-of-line is reached.

Examples to Implement of Java Console

Below are the examples of Java Console:

Example #1

Code:

import java.io.Console;
public class ConsolePrac {
public static void main(String[] args) {
Console consoleObj = null;
try {
consoleObj = System.console();
if (consoleObj != null) {
String person = consoleObj.readLine("Please enter your Name: ");
System.out.println("Welcome " + person);
System.out.println("Please check the below  result");
String fmt = "%2$8s %1$10s %3$3s%n";
consoleObj.format(fmt, "Name", "RollNo", "MArks");
consoleObj.format(fmt, "-----", "-----", "-----");
consoleObj.format(fmt, "Raj", "1212", "75");
consoleObj.printf(fmt, "Meeta", "1213", "67");
consoleObj.printf(fmt, "Sanjana", "1215", "89");
consoleObj.printf(fmt, "Pawan", "1214", "80");
}
consoleObj.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
로그인 후 복사

Output:

자바 콘솔

Example #2

Code:

import java.io.Console
import java.util.Scanner;
import java.io.PrintWriter;
public class ConsolePrac {
public static void main(String[] args) {
Console consoleObj = null;
PrintWriter PWObj = null;
String fmt1 = "%1$6s %2$5s %3$10s%n";
String fmt2 = "%1$8s %2$10s %3$5s %4$5s %5$10s%n";
Scanner scanObj = null;
try {
consoleObj = System.console();
if (consoleObj != null) {
System.out.print("Please enter your Name: ");
scanObj = new Scanner(consoleObj.reader());
String person = scanObj.next();
String empID = consoleObj.readLine(fmt1, "Please","enter","EmployeeID: ");
char[] pwd = consoleObj.readPassword("Please enter your Password: ");
char[] ans1 = consoleObj.readPassword(fmt2,"Security","question- ","Enter","your","Mothers'name: ");
PWObj = consoleObj.writer();
PWObj.println("Welcome "+person +" "+empID);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
로그인 후 복사

Output:

자바 콘솔

Note: The format string’s arguments must be the same as the String to be displayed. Please see below 2 scenarios:

Case 1: The arguments are more than specified in the format string.

String fmt= "%1$30s %2$10s"
String empID = consoleObj.readLine(fmt1, "Please","enter","your","EmployeeID: ");
로그인 후 복사

In the above case, only the first 2 strings will be printed, and others are ignored.

Case 2:  In case the arguments specified are less than a missing argument exception is thrown.

String fmt= "%1$30s %2$10s" ,"%3$10s%n"
String empID = consoleObj.readLine(fmt1, "Please","enter”);
로그인 후 복사

자바 콘솔

Note: Console program must be run using command line since eclipse gives exception while running this program.

Conclusion

Console class is one of the great utility introduced with JDK 1.6 that helps to read the input from a console instance in a secure manner. It also provides methods to write output to the console screen.

위 내용은 자바 콘솔의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!