우리는 지금까지 콘솔창에서 출력된 결과를 확인하였다. 하지만 파일로부터 입력되고 파일로 출력할 수도 있다.
java.io 패키지에 파일 입출력과 관련된 클래스가 있다.
파일은 txt, pdf, xls, csv, ppt, jpg 외에도 다양한 종류가 있다. 이러한 종류의 파일에서 입출력이 가능하다.
파일로부터 입력
먼저 byte 기반으로 파일의 데이터를 읽어보자. byte의 경우 1바이트가 할당되기 때문에 한글은 깨진다.
package oop0920;
import java.io.FileInputStream;
public class Test01_input {
public static void main(String[] args) {
// 파일 입출력(.txt)
// File : .txt .pdf .xls .csv .ppt .jpg ~~
//byte형 : 1바이트 할당
//char형 : 2바이트 할당
//1)byte 기반 -> 한글 깨짐
String filename = "I:\\java202207\\workspace\\basic01_java\\src\\oop0920\\data.txt";
FileInputStream fis = null;
try {
} catch (Exception e) {
System.out.println("파일 읽기 실패 : " + e);
} finally {
//자원반납
try {
if (fis!=null) { fis.close(); }
} catch (Exception e) {}
}//end
}//main() end
}//class end
fis에 filename을 대입하여 파일이 있는지 확인이 가능하다. 그리고 InputStream을 열었으면 이를 닫아주는 것이 필요하다.
} finally {
//자원반납
try {
if (fis!=null) { fis.close(); }
} catch (Exception e) {}
}//end
read()라는 메소드를 통해 데이터를 읽을 수 있다. read는 1byte를 읽고 int 타입으로 리턴한다. 1byte를 읽고 커서가 다음으로 이동하는데 더 이상 읽을 수 없다면 -1을 리턴한다. 반복문을 이용하여 data.txt를 읽어올 수 있다.
try {
fis = new FileInputStream(filename);
while(true) {
int data = fis.read(); //1바이트 읽기
if (data==-1) { //파일의 끝(End Of File)인지?
break;
}//if end
System.out.println(data);
}//while end
} catch (Exception e) {
int로 리턴하기 때문에 숫자로 나타난다. 이를 형 변환하여 출력하면
try {
fis = new FileInputStream(filename);
while(true) {
int data = fis.read(); //1바이트 읽기
if (data==-1) { //파일의 끝(End Of File)인지?
break;
}//if end
//System.out.println(data);
System.out.printf("%C", data);
}//while end
위와 같이 콘솔창에 출력된다.
이번에는 char 기반으로 파일로부터 입력을 해보자 FileInputStream이 byte 기반이었다면 FileReader은 char 기반이다.
package oop0920;
import java.io.FileReader;
public class Test02_input {
public static void main(String[] args) {
// 2)char 기반 -> 한글 안깨짐
String filename = "I:\\java202207\\workspace\\basic01_java\\src\\oop0920\\data.txt";
FileReader fr = null;
try {
fr = new FileReader(filename);
while(true) {
int data = fr.read(); //2byte 읽기
if(data==-1) {
break;
}//if end
System.out.printf("%C", data);
}//while end
} catch (Exception e) {
System.out.println("파일 읽기 실패 : " + e);
} finally {
//자원 반납
try {
if (fr!=null) { fr.close(); }
} catch (Exception e) {}
}//end
}//main() end
}//class end
한글이 깨지지고 않고 제대로 출력되었다.
이번에는 메모장 파일의 내용을 엔터 단위로 가져와보자
package oop0920;
import java.io.BufferedReader;
import java.io.FileReader;
public class Test03_input {
public static void main(String[] args) {
// 3) 메모장 파일의 내용을 엔터 단위로 가져오기
String filename = "I:\\java202207\\workspace\\basic01_java\\src\\oop0919\\Order.java";
FileReader fr = null;
BufferedReader br = null;
try {
//1)파일 가져오기
fr = new FileReader(filename);
//2)파일 내용 읽기
br = new BufferedReader(fr);
int num = 0; //행번호
while(true) {
String line = br.readLine(); //3)엔터(\n)를 기준으로 한 줄씩 가져오기
if(line==null) { //파일의 끝인지? (EOF)
break; //반복문 빠져나감
}//if end
System.out.printf("%d %s\n", ++num, line);
//20행마다 밑줄 긋기
if(num%20==0) {
System.out.println("-------------------------");
}//if end
}//while end
} catch (Exception e) {
System.out.println("파일 읽기 실패 : " + e);
} finally {
//자원 반납 순서 주의
try {
if(br!=null) { br.close(); }
} catch (Exception e) {}
try {
if(fr!=null) { fr.close(); }
} catch (Exception e) {}
}//end
}//main() end
}//class end
파일로 출력
파일에 출력하려고 할 때 해당 파일이 없으면 새로 파일이 생성되고, 파일이 있으면 덮어쓰거나 추가할 수 있다.
package oop0920;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class Test04_output {
public static void main(String[] args) {
// 메모장 파일에 출력하기
//출력파일(sungjuk.txt)이
//->없으면 파일은 생성된다(create)
//->있으면 덮어쓰기(overwrite) 또는 추가(append)
String filename = "I:\\java202207\\sungjuk.txt";
FileWriter fw = null;
PrintWriter out = null;
try {
//true : append 모드
//false : overwrite 모드
fw = new FileWriter(filename, true);
//autoFlush : true 버퍼클리어
out = new PrintWriter(fw, true);
//oop0906.Test01_format.java 참조
//out.printf();
out.println("무궁화,95,90,100");
out.println("홍길동,100,100,100");
out.println("라일락,90,95,35");
out.println("개나리,85,70,75");
out.println("진달래,35,40,60");
System.out.println("sungjuk.txt 데이터 파일 완성!!");
} catch (Exception e) {
System.out.println("파일 쓰기 실패 : " + e);
} finally {
//자원 반납
try {
if(out!=null) { out.close(); }
} catch (Exception e) {}
try {
if(fw!=null) { fw.close(); }
} catch (Exception e) {}
}//end
}//main() end
}//class end
여기서 append가 가능하게 해주었다.
//true : append 모드
//false : overwrite 모드
fw = new FileWriter(filename, true);
따라서 실행을 할 때마다 sungjuk.txt에 계속 입력이 된다.
//true : append 모드
//false : overwrite 모드
fw = new FileWriter(filename, false);
이번에는 false로 바꾸어 덮어쓰도록 하였다.
여러 번 실행해도 추가가 되지 않고 덮어써진다.
'웹개발 교육 > Java' 카테고리의 다른 글
[39일] Java (52) - 성적 프로그램(파일 입출력) (0) | 2022.09.21 |
---|---|
[38일] Java (51) - type (0) | 2022.09.20 |
[37일] Java (49) - File 클래스 (0) | 2022.09.19 |
[37일] Java (48) - Thread (0) | 2022.09.19 |
[37일] Java (47) - 상품 구매 및 반품 프로그램 (0) | 2022.09.19 |