Java를 사용하여 파일을 읽어야 하는 경우 여러가지 방법이 있지만, 그 중 2가지 방법을 소개하고자 한다.
- Files.readAllLines(Path)
- Files.newBufferedReader(Path) & readLine()
Files.readAllLines(Path)
Path path = Path.of("/users/user/document/text.txt");
try {
List<String> content = Files.readAllLines(path);
for(String line : content) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("File open failed : " + e.getMessage());
} catch (SecurityException e) {
System.out.println("Access permission failed");
}
Path.of() 메서드를 사용하여 특정 파일 경로를 갖는 Path 객체를 생성
Files.readAllLines() 메서드를 호출하여 해당 파일의 모든 라인을 읽어서 List<String>으로 반환
이후 해당 리스트의 요소를 읽으면 끝
이때, Files.readAllLines() 메서드의 동작으로 인해 읽고자 하는 파일의 크기가 크다면 메모리에 문제가 발생할 수 있기 때문에 작은 크기의 파일을 읽을 때에만 사용하는 것이 좋을 것으로 보인다.
또한 해당 경로의 파일을 읽을 수 없다면 IOException이 발생하고, 예외의 message에는 파일 경로가 들어간다.
만약 해당 경로의 파일에 대한 접근 권한이 없다면 SecurityException 발생
Files.newBufferedReader(Path) & readLine
Path path = Path.of("/users/user/document/text.txt");
try {
BufferedReader br = Files.newBufferedReader(path);
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("File open failed : " + e.getMessage);
} catch (SecurityException e) {
System.out.println("Access permission failed");
}
Path.of() 메서드를 사용하여 특정 파일 경로를 갖는 Path 객체를 생성
Files.newBufferedReader() 메서드를 호출하여 해당 파일을 읽는 BufferedReader 객체 반환
BufferedReader의 readLine() 메서드를 사용하여 라인 단위로 읽으면 끝
이는 라인 단위로 파일을 읽기 때문에 파일의 사이즈가 크더라도 readAllLines() 메서드와 같이 메모리 문제가 발생하지 않는다.
따라서 사이즈가 큰 파일을 읽어야 할 때에는 해당 방식을 사용하는 것이 좋을 것으로 보인다.
예외의 경우 readAllLines() 메서드와 동일한 이유로 IOExcetpion, SecurityException이 발생할 수 있다.
ClassPathResource
아래의 방법으로 Spring project의 resource 경로에 존재하는 파일에 쉽게 접근이 가능하다고 하는데..
나는 resource 경로가 아닌 Spring proejct의 root 경로를 기본값으로 사용하여 파일을 찾더라
살짝 찾아본 결과 ClassPath 라는 환경 변수(?)를 기본 경로로 잡는다고 하는데, 따로 설정이 안되어 있다면 어플리케이션 실행 위치를 기본 경로로 잡는다고 한다.
ClassPath가 지정이 안되어 있어서 root 경로를 기본값으로 사용하여 찾게 된 것 같은데.. 나중에 좀 더 자세히 찾아봐야 할 것 같다.
ClassPathResource resource = new ClassPathResource("user.txt");
Path path = Path.of(resource.getPath());
'Develop > Java' 카테고리의 다른 글
Spring MVC 간단 정리 (0) | 2023.02.14 |
---|---|
Spring 기동시 bean 초기화 메서드 호출 방법 (0) | 2022.11.29 |
JPA Fetch Type (1) | 2022.09.09 |
Collection framwork (0) | 2022.07.26 |
제네릭(Generic)이란? (0) | 2022.07.25 |