WebBack/Java
[Java] Files.readAllLines 사용법
ycraah
2024. 6. 19. 21:38
Files.readAllLines란?
파일의 모든 줄을 읽어서 List<String> 형태로 반환하는 메서드
Files 클래스에 정의되어 있음
메서드 요약
public static List<String> readAllLines(Path path, Charset cs) throws IOException {
try (BufferedReader reader = newBufferedReader(path, cs)) {
List<String> result = new ArrayList<>();
for (;;) {
String line = reader.readLine();
if (line == null)
break;
result.add(line);
}
return result;
}
}
public static List<String> readAllLines(Path path) throws IOException {
return readAllLines(path, UTF_8.INSTANCE);
}
이 메서드는 다음과 같은 매개 변수를 받는다.
1. (Path 객체)
2. (Path 객체, Charset 객체)
메서드 사용법
Files.readAllLines은 다음과 같이 사용된다.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.nio.charset.StandardCharsets;
public class test {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
// 파일의 모든 줄을 읽고 리스트로 반환
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// 읽은 내용 출력
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
참고로 StandardCharsets.UTF_8은 UTF-8인코딩을 가리킨다.
이는 파일을 읽을 때에 사용할 문자 인코딩을 지정한다.
UTF-8은 호환성과 범용성이 높아 많이 사용된다.
Files (Java Platform SE 8 )
Copy a file to a target file. This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target
docs.oracle.com