- 파일에 쓰기 = 파일에 출력하기 = 기록하기
- 만약 파일이 없는 경우 (자동) 생성 후에 쓰기 작업이 됨
- 만약 파일이 있었다면, 덮어쓰기가 된다
쓰기 (Write)
1. 한 문장씩 쓰기
: FileWriter
File file = new File("e:\\test.txt");
String str = "반갑습니다";
try {
// 쓰기 작업 (덮어쓰기 됨; 매번 새로 쓰기)
FileWriter fw = new FileWriter(file); // fw는 접근자
fw.write(str + "\n");
fw.close(); // 반드시 닫아주어야 함!!
} catch (IOException e) {
throw new RuntimeException(e);
}
1-2. 이어서 쓰기 (append)
: FileWriter
// 추가 쓰기 작업
FileWriter fw = new FileWriter(file, true); // append = 추가
fw.write("건강하세요");
fw.close();
2. 문장으로 쓰기
: FileWriter + BufferedWriter + PrintWriter
// 문장으로 쓰기
String[] strArr = { "홍길동", "성춘향", "일지매" };
try {
FileWriter fw3 = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw3); // Buffer = 저장공간
PrintWriter pw = new PrintWriter(bw);
/*pw.println("하이");
pw.println("건강하세요");
pw.println("성공하세요");*/
for (String s: strArr) {
pw.println(s);
}
pw.close(); // 반드시 닫아주기
} catch (IOException e) {
throw new RuntimeException(e);
}
파일 읽기
1. 한 문자씩 읽기
FileReader
File file = new File("E:\\test.txt");
// 한 문자씩 읽기
try {
FileReader fr = new FileReader(file);
String str = "";
int c = fr.read();
// 파일의 끝부분까지 읽어오기 -> 루프 사용
while ( c != -1) { // -1은 파일의 끝임.
str = str + (char)c; // 읽어오고서,
c = fr.read(); // 데이터 갱신
}
fr.close(); // '읽기' 작업에서는 close가 덜 중요함
System.out.println(str);
} catch (FileNotFoundException e) {
// 파일 '쓰기'는 파일이 없으면 새로 생성하지만,
// 파일 '읽기'는 파일이 없으면 읽어올 수 없음!
throw new RuntimeException(e);
} catch (IOException e) {
// .read() 메소드에서도 예외 처리 필요
throw new RuntimeException(e);
} catch (Exception e) {
// 포괄 예외 처리 Exception
throw new RuntimeException(e);
}
2. 문장 단위로 읽기 : readLine
FileReader
BufferedReader
// 문장으로 읽기
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str = "";
// 첫번째 방법
String names = "";
while ((str = br.readLine()) != null) {
//System.out.println(str);
names = names + str + "\n";
}
br.close();
//System.out.println(str);
System.out.println(names);
} /*catch (FileNotFoundException e) {
throw new RuntimeException(e);
}*/ catch (Exception e) {
throw new RuntimeException(e);
}
'Java > Java 기본 문법' 카테고리의 다른 글
| [Java] 접근 지정자 (private, public, protected) (1) | 2025.01.06 |
|---|---|
| [Java] 예외 처리 (Exception, Try-Catch, throws) + 대표적인 예외 처리들 + 기초적인 포인터 개념 (2) | 2025.01.02 |
| [Java] 파일 입출력 1 (경로 검색, 생성하기, 존재 여부, 읽기/쓰기 가능 여부, 삭제하기) (1) | 2025.01.02 |
| [Java] 문자열 슬라이싱 (Split 메소드) (1) | 2025.01.02 |
| [Java] 값 할당 vs 메모리 주소 할당 (데이터 타입에 따른 할당의 차이) with 함수 (0) | 2024.12.31 |