파일 입출력 시 BufferedReader를 사용하면 편리!!
1. FileReader
- 파일을 읽어 화면에 출력
- 파일을 자바가 설치된 폴더에 저장해야 자동 인식
- 경로를 따로 지정할 수 있음
package ex18;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample01 {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("test.txt");
int ch;
// fr 버퍼에서 내용을 읽었을때, 내용이 없으면 -1을 읽음 (그때 while 종료하면 됨)
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Code Tuning : BufferedReader 사용
- 결과는 동일
package ex18;
import java.io.*;
public class FileReaderEx01 {
public static void main(String[] args) {
try {
// FileReader 대신 BufferedReader 사용
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("test.txt"))
);
// 1줄씩 읽음, 마지막 줄에서 ready = false (내용이 없음)이므로 break
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2. 파일 복사
- FileReader, FileWriter를 사용하여 내용을 복사하여 다시 작성
package ex18;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFile01 {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("test.txt");
FileWriter fw = new FileWriter("copy.txt");
int c;
while ((c = fr.read()) != -1) {
fw.write(c);
}
// try-with-resources 구문 사용 시 try 종료 후 자동 close
fr.close();
fw.close();
System.out.println("Copy Done");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}


3. FileStream
- 파일을 바이트 단위로 읽어서 저장
- 이진 파일은 직접 읽을 수 없음 : Binary File Reader 프로그램이 필요
package ex18;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamTest01 {
public static void main(String[] args) {
byte list[] = {10, 20, 30, 40, 50, 60};
// try-with-resources
try (FileOutputStream out = new FileOutputStream("test.bin")) {
for (byte b : list) {
out.write(b);
}
System.out.println("Done");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

- 이진 파일을 읽어와서 모니터에 출력
package ex18;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileStreamTest02 {
public static void main(String[] args) {
byte[] list = new byte[6];
try (FileInputStream out = new FileInputStream("test.bin")) {
out.read(list);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (byte b : list) {
System.out.print(b + " ");
}
System.out.println();
}
}

4. 이미지 복사
- 이미지는 이진 파일이므로 Byte Stream을 사용해야 함
package ex18;
import java.io.*;
import java.util.Scanner;
public class ByteStreamEx {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// png 파일이므로 파일 이름만 입력하면 자동으로 확장자를 추가하도록 코드 수정
System.out.print("원본 파일 이름을 입력하시오: ");
String inputFileName = sc.next() + ".png";
System.out.print("복사 파일 이름을 입력하시오: ");
String outputFileName = sc.next() + ".png";
try (InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName)) {
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(inputFileName + "을 " + outputFileName + "으로 복사하였습니다.");
}
}

- 원본 java와 복사된 java_copy, java_copy_2

5. DataStream
- 여러 Byte Stream을 모아서 정수 또는 글자로 처리할 수 있는 Stream
package ex18;
import java.io.*;
public class DataStreamTest01 {
public static void main(String[] args) throws IOException {
DataInputStream in = null;
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream("data.bin"));
out.writeInt(123);
out.writeFloat(123.456f);
out.close();
in = new DataInputStream(new FileInputStream("data.bin"));
int aint = in.readInt();
float afloat = in.readFloat();
System.out.println(aint);
System.out.println(afloat);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

- 이진 파일로 생성된 data.bin

6. BufferedStream
- 버퍼(Buffer)를 사용한 Stream, 오버헤드를 줄여 처리 속도 감소
package ex18;
import java.io.*;
public class CopyLines {
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"))) {
String line;
while ((line = in.readLine()) != null) {
// 줄 단위로 출력 : Buffer
out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}


7. Character Encoding
- encoding된 유형에 따라 글자가 깨질 수 있음
- 파일을 읽는 encoder를 맞추어 주면 글자가 깨지지 않고 잘 출력됨
package ex18;
import java.io.*;
public class CharEncodingTest {
public static void main(String[] args) throws IOException {
File fileDir = new File("input.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}

8. Copy Lines
- 한 줄 단위로 입력받은 후 그 줄을 복사
- BufferedReader, PrintWriter 사용
package ex18;
import java.io.*;
public class CopyLines02 {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
// BufferedReader와 FileReader를 연결
inputStream = new BufferedReader(new FileReader("input.txt"));
// PrintWriter와 FileWriter를 연결
outputStream = new PrintWriter(new FileWriter("output.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

9. 객체 저장
- 역직렬화(deserialization) 활용
package ex18;
import java.io.*;
import java.util.Date;
public class ObjectStreamTest {
public static void main(String[] args) throws Exception {
ObjectInputStream in = null;
ObjectOutputStream out = null;
int c;
// 현재 시간 객체를 파일에 작성
out = new ObjectOutputStream(new FileOutputStream("object.dat"));
out.writeObject(new Date());
out.close();
// 작성한 객체 파일을 읽어옴
in = new ObjectInputStream(new FileInputStream("object.dat"));
Date d = (Date) in.readObject();
System.out.println(d);
in.close();
}
}

10. 파일 속성 표시
- path, file 객체를 사용하여 file의 속성 표시
package ex18;
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException {
String name = "C:\\workspace\\java_lec\\study";
File dir = new File(name);
String[] fileNames = dir.list();
for (String s : fileNames) {
// 절대 경로 지정 : 이름을 주어야 함
File f = new File(name + "/" + s);
System.out.println("-------------------------------");
System.out.println("이름 : " + f.getName());
System.out.println("경로 : " + f.getPath());
System.out.println("부모 : " + f.getParent());
System.out.println("절대 경로 : " + f.getAbsolutePath());
System.out.println("정규 경로 : " + f.getCanonicalPath());
System.out.println("디렉토리 여부 : " + f.isDirectory());
System.out.println("파일 여부 : " + f.isFile());
System.out.println("-------------------------------");
}
}
}

Share article