프로그래밍/Java

[자바/java] File BufferedReader 활용 특정 파일 실행, 문자찾기

Rolen 2023. 1. 31. 21:05

확장명이 java 인 파일들의 이름을 출력 후 실행하고

해당 파일내에 class 라는 단어가 들어가는 해당 줄의 번호와 모든 글자를 출력.

package q8;

import java.io.*;
import java.nio.*;
import java.util.*;

public class Q8 {

	public static void main(String[] args) throws IOException {
		Scanner sc;
		File file = new File("//파일경로입력-----------------q");
		String fileNames[] = file.list();
		String javaFile;
		int count;
		for (String str : fileNames) {
			String ext = str.substring(str.lastIndexOf(".") + 1);
			if (ext.equals("java")) {
				System.out.print(str + "\n");
				BufferedReader in = new BufferedReader(new FileReader("//파일경로입력-----\\"+str));
				String strLine;
				count = 1;
				while ((strLine = in.readLine()) != null) {
					sc = new Scanner(strLine);
					while (sc.hasNext()) { // hasNext() = 읽어올 다음 문자가 없으면 false, 있으면 true. 
						if (sc.next().equals("class")) {
							System.out.printf("%d line : %s\n", count, strLine);
						}
					}
					count++;
				}
			}
		}
	}

}

담긴 파일목록 / 결과 console

 

728x90