Java 문자 터미널에서 입력 공유
1、java.lang.System.in(현재 JDK 버전은 지원) 2,java.util.Scanner(JDK 버전 >=1.5) 3, java.io.Console(JDK 버전 >=1.6), 특징: 암호 문자가 표시되지 않음
참고: 여기에는 Java에서 콘솔에서 정보를 읽어들이는 몇 가지 방법이 기록되어 있습니다. (1) JDK 1.4(JDK 1.5와 JDK 1.6도 모두 호환됩니다.)
public class TestConsole1 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:);
System.out.println("The information from console: + str);
}
/**
* Use InputStreamReader and System.in to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try {
System.out.print(prompt);
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
(2) JDK 1.5(Scanner를 사용하여 읽기)
public class TestConsole2 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:");
System.out.println("The information from console:" + str);
}
/**
* Use java.util.Scanner to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
Scanner scanner = new Scanner(System.in);
System.out.print(prompt);
return scanner.nextLine();
}
}
Scanner는 또한 파일을 스캔하여 안에 있는 정보를 읽고 원하는 형식으로 변환할 수 있습니다. 예를 들어 "22.23.33.334.5done"과 같은 데이터의 조화를 구하려면 다음과 같은 코드를 보십시오
public class TestConsole4 {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("num.txt");
fw.write("2 2.2 3.3 3.33 4.5 done");
fw.close();
System.out.println("Sum is "+scanFileForSum("num.txt"));
}
public static double scanFileForSum(String fileName) throws IOException {
double sum = 0.0;
FileReader fr = null;
try {
fr = new FileReader(fileName);
Scanner scanner = new Scanner(fr);
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
sum = sum + scanner.nextDouble();
} else {
String str = scanner.next();
if (str.equals("done")) {
break;
} else {
throw new RuntimeException("File Format is wrong!");
}
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File " + fileName + " not found!");
} finally {
if (fr != null)
fr.close();
}
return sum;
}
}
(3) JDK 1.6(java.io.Console을 이용하여 읽기) JDK6에서java를 제공합니다.io.Console 클래스 전용으로 문자 기반 콘솔 장치에 액세스합니다.프로그램이 Windows 아래의 cmd나 Linux 아래의 Terminal과 상호작용하려면 Console 클래스로 대체할 수 있습니다.(System.in과 System.out과 같은) 그러나 우리는 항상 사용할 수 있는 Console을 얻을 수 있는 것은 아니다. 하나의 JVM이 사용할 수 있는 Console이 있는지의 여부는 기본 플랫폼과 JVM이 어떻게 호출되는지에 의존한다.만약 JVM이 상호작용 명령행(예를 들어 Windows의 cmd)에서 시작되고 입력과 출력이 다른 곳으로 바뀌지 않았다면 사용할 수 있는 콘솔 실례를 얻을 수 있을 것이다.IDE를 사용하는 경우 Console 인스턴스를 가져올 수 없습니다. IDE 환경에서 표준 입력과 출력 흐름을 재정의하거나 시스템 콘솔의 입력과 출력을 IDE 콘솔로 재정의하기 때문입니다
public class TestConsole3 {
public static void main(String[] args) {
String str = readDataFromConsole("Please input string:");
System.out.println("The information from console:" + str);
}
/**
* Use java.io.console to read data from console
*
* @param prompt
*
* @return input string
*/
private static String readDataFromConsole(String prompt) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("Console is not available!");
}
return console.readLine(prompt);
}
}
Console 클래스의 또 다른 특징은 비밀번호 (입력에 회신이 없음) 등 보안 문자를 처리하는 것이다.readPassword() 방법을 전문적으로 제공하며, 구체적인 응용 프로그램은 다음과 같다
public class TestConsole5 {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("Console is not available!");
}
while(true){
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");
if (username.equals("Chris") && String.valueOf(password).equals("GoHead")) {
console.printf("Welcome to Java Application %1$s.
", username);
// , ,
password = null;
System.exit(-1);
}
else {
console.printf("Invalid username or password.
");
}
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.