코딩.zip
[Java] 파일 입출력 본문
🌱 파일 처리
파일처리를 위해 java.io 패키지 포함해야 한다.
입출력 스트림 유형
- 바이트 스트림
- OutputStream 클래스
- InputStream 클래스 - 문자 스트림
- Reader 클래스
- Writer 클래스
1️⃣ 파일 생성
File 클래스 : 생성, 삭제, 이름변경, 디렉터리 내용 나열 등 다양한 작업 수행하는 메서드 포함되어 있다.
- example01.txt File 생성
🚨 boolean 값으로 받는 createNewFile()은 파일이 있으면 false, 없으면 true 값을 가진다.
⌗ createNewFile() : 원하는 경로에 새 파일 생성, 보통 생성된 파일은 비어 있다.
package chap12;
import java.io.File;
import java.io.IOException;
public class Example01 {
public static void main(String[] args) {
File fileObj = new File("example01.txt");
try {
// 새로운 파일 생성
boolean success = fileObj.createNewFile();
// 중복 생성 방지 : 파일이 있으면 false
if(success) {
System.out.println("파일 생성 성공");
}
else {
System.out.println("파일 생성 실패");
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
- Example01.java 파일 정보 얻어오기
package chap12;
import java.io.File;
public class FileHandling01 {
public static void main(String[] args) {
File finfo = new File("./src/chap12/Example01.java");
if(finfo.exists()) {
System.out.println("파일의 이름 : " + finfo.getName());
System.out.println("파일의 경로 : " + finfo.getAbsolutePath());
System.out.println("파일 쓰기가 가능한가? : " + finfo.canWrite());
System.out.println("파일 읽기가 가능한가? : " + finfo.canRead());
System.out.println("파일의 크기 : " + finfo.length());
}
else {
System.out.println("파일이 존재하지 않습니다.");
}
}
}
/* 실행 결과
* 파일의 이름 : Example01.java
* 파일의 경로 : /Users/Chap12/./src/chap12/Example01.java
* 파일 쓰기가 가능한가? : true
* 파일 읽기가 가능한가? : true
* 파일의 크기 : 439
*/
2️⃣ 파일 쓰기
✅ OutputStream 클래스 (바이트 출력 스트림)
- FileOutputStream 클래스 : 파일에 데이터를 쓰는 데 사용되는 출력 스트림
💡 void write(byte[] b) - 바이트 배열의 b.length 바이트를 파일 출력 스트림에 사용
package chap12;
import java.io.File;
import java.io.FileOutputStream;
public class FileHandling02 {
public static void main(String[] args) {
File file = new File("gugudan.txt");
try {
if (!file.exists()) {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
for (int x = 2; x <= 9; x++) {
for (int y = 1; y <= 9; y++) {
String str = x + "X" + y + "=" + (x + y) + "\n"; // 문자열로 구구단을 받고
byte[] b = str.getBytes(); // 구구단 문자열을 바이트 배열로 받은 후
fos.write(b); // 바이트 배열의 b.length 바이트를 파일 출력 스트림에 사용
}
}
fos.close(); // 파일 출력 스트림 닫기
System.out.println("파일 쓰기 성공");
}
} catch (Exception e) {
e.getMessage();
}
}
}
✅ Writer 클래스 (문자 출력 스트림)
- FileWriter 클래스 : 문자 데이터를 파일에 쓰는데 사용
💡 void write - 문자열을 직접 쓰는 방법을 제공하므로 문자열을 바이트 배열로 변환 할 필요 없음
package chap12;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class FileHandling03 {
public static void main(String[] args) {
File file = new File("member.txt");
try {
if (!file.exists()) {
file.createNewFile();
//FileWriter fw = new FileWriter(file);
FileWriter fw = new FileWriter(file, true); // true : 이어쓰기 가능
Scanner input = new Scanner(System.in);
boolean quit = false;
while (!quit) {
System.out.println("아이디 : ");
String userID = input.next();
fw.write("아이디 : " + userID + " ");
System.out.println("이름 : ");
String userName = input.next();
fw.write("이름 : " + userName + " ");
System.out.println("계속 진행 ? Y | N ");
input = new Scanner(System.in);
String str = input.next();
if (str.toUpperCase().equals("N")) {
quit = true;
}
fw.close();
System.out.println("파일 쓰기 성공");
}
}
} catch (Exception e) {
e.getMessage();
}
}
}
3️⃣ 파일 읽기
✅ InputStream 클래스 (바이트 입력 스트림)
-FileInputStream 클래스 : 파일에서 읽는 입력 스트림, 바이트 지향 데이터
💡read() - 입력 스트림에서 데이터 바이트를 읽음, 파일 끝에서 -1 반환
package chap12;
import java.io.File;
import java.io.FileInputStream;
public class FileHandling04 {
public static void main(String[] args) {
File file = new File("gugudan.txt");
try {
if(!file.exists())
file.createNewFile();
// 바이트 스트림을 읽어오는데 사용되는 입력 스트림
FileInputStream fis = new FileInputStream(file);
int i = 0;
while ((i = fis.read()) != -1 ) {
System.out.print((char) i);
}
fis.close();
System.out.println("파일 읽기 성공");
}
catch (Exception e) {
System.out.println(e);
}
}
}
✅ Reader 클래스 : 문자 스트림을 읽기 위한 추상 클래스, 문자 지향 데이터
-FileReader 클래스 : 문자 지향 데이터 읽는데 사용
💡read() - ASCII 형식 문자 반환, 파일 끝에서 -1 반환
package chap12;
import java.io.File;
import java.io.FileReader;
public class FileHandling05 {
public static void main(String[] args) {
File file = new File("member.txt");
try {
if (!file.exists())
file.createNewFile();
// 문자 지향 데이터 읽어오기
FileReader fis = new FileReader(file);
int i = 0;
while ((i = fis.read()) != -1) {
System.err.print((char) i);
}
fis.close();
System.out.println("파일 읽기 성공");
}
catch (Exception e) {
System.out.println(e);
}
}
}
- BufferedReader 클래스 : 문자 기반 입력 스트림에서 텍스트를 읽는데 사용
💡readLine() - 데이터를 한 줄씩 읽을 때 사용해서 성능 향상에 도움
package chap12;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileHandling06 {
public static void main(String[] args) {
File file = new File("member.txt");
try {
if (!file.exists())
file.createNewFile();
FileReader fis = new FileReader(file);
BufferedReader br = new BufferedReader(fis); // 문자 기반 입력 스트림에서 텍스트를 읽음
String str;
// readLine() : 데이터를 한 줄씩 읽어오기 때문에 int가 아닌 string으로 받아올 수 있다.
while ((str = br.readLine()) != null) {
System.out.println(str);
}
fis.close();
System.out.println("파일 읽기 성공");
}
catch (Exception e) {
System.out.println(e);
}
}
}
'프로그래밍 > Java' 카테고리의 다른 글
[Java] Object class - toString(), equals() 메서드 (0) | 2024.06.01 |
---|---|
스프링 MVC STS3, STS4 설치 (0) | 2024.05.13 |
[Java] 컬렉션 프레임워크 (0) | 2024.05.02 |
[Java] 추상화 (0) | 2024.04.15 |
[Java] 클래스(Class) (0) | 2024.04.15 |