목차
- 파일 읽기
- 파일 정보 얻기
- 파일 제어 관련글
파일 읽기
1.
Scanner 클래스 안의 hasNextLine(), nextLine() 메서드 사용.
※ hasNextLine() : 라인 유무 체크.
※ nextLine() : 라인 읽기.
2.
FileNotFoundException 오류 발생 (파일 미존재) 대비해,
try...catch... 구문 안에서 사용해야 함.
[예제] ReadFile.java
import java.io.File; // 파일 (생성,쓰기) 클래스
import java.io.FileNotFoundException; // 에러 제어 클래스
import java.util.Scanner; // 파일 읽기 클래스
public class ReadFile {
public static void main(String[] args) {
try {
File hz = new File("homzzang.txt");
Scanner hzscan = new Scanner(hz);
while (hzscan.hasNextLine()) {
String data = hzscan.nextLine();
System.out.println(data);
}
hzscan.close();
} catch (FileNotFoundException e) {
System.out.println("에러 발생.");
e.printStackTrace();
}
}
}
결과값: 홈짱닷컴 Homzzang.com
파일 정보 얻기
File 클래스 안의 여러 메서드 활용.
[예제] GetFileInfo.java 생성.
import java.io.File; // 파일 제어
public class GetFileInfo {
public static void main(String[] args) {
File hz = new File("homzzang.txt");
if (hz.exists()) {
System.out.println("파일명 : " + hz.getName());
System.out.println("절대경로 : " + hz.getAbsolutePath());
System.out.println("쓰기 가능? : " + hz.canWrite());
System.out.println("읽기 가능? : " + hz.canRead());
System.out.println("파일사이즈 (byte단위) : " + hz.length());
} else {
System.out.println("파일 존재 X.");
}
}
}
PS.
1. Java API의 파일 제어 클래스 종류
- FileReader
- BufferedReader
- Files
- Scanner
- FileInputStream
- FileWriter
- BufferedWriter
- FileOutputStream
2. 사용할 클래스는 아래 경우에 따라 다름.
① 작업 중인 Java 버전.
② 읽거나 쓸 크기. (예: 바이트/문자 수준인지, 파일/라인 수준인지)
파일 제어 관련글
파일 제어
https://homzzang.com/b/java-50
파일 생성/쓰기
https://homzzang.com/b/java-51
파일 읽기 (※ 현재 위치.)
https://homzzang.com/b/java-52
파일 삭제
https://homzzang.com/b/java-53