K-DigitalTraining 강의/1. Java

[5주차] 86. 파일에서 구분자로 구분해 읽어오는 코드, Scanner의 다른 생성자를 이용

이대곤 2022. 6. 8. 09:52

파일에서 구분자로 구분해 읽어오는 코드

- test.txt를 생성한 상태에서 실행해야 하며, 파일의 내용은 "1,2,3,4,5,6,7,8,9,10" 였다.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Ex11_10_Scanner {
	public static void main(String[] args) {
		
//		Scanner sc = new Scanner(System.in); // Scanner(InputStream source) 생성자 사용
//		System.out.print("입력");
//		int a = sc.nextInt();
		
		File f = new File("test.txt");
		Scanner sc = null;
		try {
			sc = new Scanner(f); // 사용자 입력이 아닌 파일에서 Scanner로 읽어올 때 이 생성자를 사용 Scanner(File source)
			sc.useDelimiter(","); 		// 구분자로 쉽표로 끊어 읽어라(이걸 안해주면 한 줄을 통으로 읽음)
			
			int num, sum = 0, cnt = 0;
			
			while(sc.hasNextInt()) {
				num = sc.nextInt();
				System.out.println(num);
				sum += num;
				cnt++;
			}
			
			System.out.println("sum:" + sum);
			System.out.println("avg:" + (sum / cnt));
			
		} catch (FileNotFoundException e) { 
			e.printStackTrace();
		}
	}
}

실행결과

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
sum:55
avg:5