사용자의 키보드 제어만이 입력은 아니다. 아래 예제는 out.txt라는 파일을 입력 받아서 화면에 출력하는 예를 보여주고 있다. 예제를 실행하려면 프로젝트의 루트 디렉토리(src와 bin 디렉토리가 위치하고 있는 경로)로 이동해서 아래와 같이 명령을 실행한다. out.txt 파일이 존재해야 한다. 이에 대한 자세한 이야기는 동영상을 참고하자.
package org.opentutorials.javatutorials.io; import java.util.Scanner; import java.io.*; public class Scanner3Demo { public static void main(String[] args) { try { File file = new File("out.txt"); Scanner sc = new Scanner(file); while(sc.hasNextInt()) { System.out.println(sc.nextInt()*1000); } sc.close(); } catch(FileNotFoundException e){ e.printStackTrace(); } } }
실행결과
input.txt 에 입력한 값 * 1000