카테고리 없음

[Java] 기본 API 클래스④ Scanner 클래스

망고고래 2024. 4. 3. 16:11

what?

문자데이터를 읽어오는 클래스

File, InputStream, String, Readable 등의 타입을 읽어옴

 

how?

1) 화면으로 입력받기: System.in

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

 

입력받을 값의 타입에 따라 사용하는 메서드가 달라짐

String: nextLine()

int: nextInt()

boolean: nextBoolean()

byte: nextByte()

short: nextShort()

long: nextLong()

 

 

2) 파일에서 값 읽어오기: FileInputStream

//파일이 없을 수 있기 때문에 예외 처리 필요
try{
    //Scanner 인스턴스 생성: FileInputStream 클래스를 통해 파일을 한 줄씩 읽어들임
    FileInputStream fis = new FileInputStream("src\\efefe\\sample.txt");
    Scanner sc = new Scanner(fis);
    
    //값이 존재하면 반복
    while(sc.hasNext()){
        System.out.println(sc.nextLine());
    }
}
catch(Exception e)}
    e.printStackTrace();
}