Binary World

JAVA CLASS : 파일 입출력(File 클래스) 01 - 기본 정의 및 사용 본문

개발자의 길/JAVA

JAVA CLASS : 파일 입출력(File 클래스) 01 - 기본 정의 및 사용

모쿠 2017. 1. 12. 18:35

<파일 입출력(File 클래스)>


* 프로그램에 파일을 저장하거나 불러오고 수정할 때 사용하는 클래스

* 방법에 따라 속도가 달라짐

* 프로그램과 입출력 장치와의 관계

- 프로그램 <=== InputStream <=== 입력 장치(키보드, 마우스, 파일, ...)

- 프로그램 ===> OutputStream ===> 출력장치(모니터, 프로젝터, 프린터, 파일, ...)


* 파일의 입출력 단계

- 프로그램 <=== InputStream <=== 입력장치

- 프로그램 <=== FileInputStream <=== 파일

- FileInputStream 클래스의 read() 메소드를 사용해서 파일을 읽음


- 프로그램 ===> OutputStream ===> 출력장치

- 프로그램 ===> FileOutputStream ===> 파일

- FileOutputStream 클래스의 write() 메소드를 사용해서 파일에 씀


* 버퍼를 이용한 파일 입출력 단계

- 프로그램 <== FileInputStream <== 파일(HDD)

- FileInputStream의 read() 메소드는 HDD를 직접 접근 -> 속도 느림

- 프로그램 <== BufferdInputStream <== FileInputStream <== 파일(HDD)

- BufferedInputStream의 read() 메소드는 메모리 버퍼에서 읽음 -> 속도 빠름


- 프로그램 ==> FileOutputStream ==> 파일(HDD)

- FileOutputStream의 write() 메소드는 HDD를 직접 접근 -> 속도 느림

- 프로그램 <== BufferedOutputStream ==> FileOutputStream ==> 파일(HDD)

- BufferedOutputStream의 write() 메소드는 메모리 버퍼에 데이터를 씀 -> 속도 빠름



<프로그램 코드>

1. 파일 입출력과 예외처리

* FileMain02.java

package edu.java.file02;



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;



public class FileMain02 {


public static void main(String[] args) {

InputStream in = null;

OutputStream out = null;

try {

// 파일에서 데이터를 읽어 올 통로인 FileInputStream 객체 생성

in = new FileInputStream("temp/original.txt");

// 파일에 데이터를 쓸 통로인 FileOutputStream 객체 생성

out = new FileOutputStream("temp/good.txt");

int data = 0; // read() 메소드가 리턴하는 값을 저장할 변수

int byteCopied = 0; // write() 메소드를 호출할 때 마다 1씩 증가

while (true) {

// read(): 파일에서 1바이트씩 데이터를 읽어옴

// 파일 끝에 도달했을 때 -1을 리턴

data = in.read();

if(data == -1){

break; // while문 종료

}

// write(): 1바이트씩 파일 씀

out.write(data);

byteCopied++;

} // end while (true)

System.out.println(byteCopied + "바이트 복사됨");

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

if (in != null){

in.close();

}

if (out != null){

out.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

} // end main()


} // end class FileMain02


* 출력화면


49바이트 복사됨 



2. Java 7 부터 사용 가능한 try-with-resource 구문


* FileMain03.java


package edu.java.file03;


import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;


/*


1. 일반적인 try-catch-finally 구문

try {

...(실행문);

} catch (Exception e) {

...(예외 처리);

} finally {

...(항상 실행할 코드들); // 리소스 해제

}


2. try-with-resource 구문: Java 7버전부터 제공

   try () 안에서 생성된 리소스들의 해제 코드(close();)는 자동으로 호출됨

try (리소스 생성;) {

실행문;

} catch (Exception e) {

예외처리;

}


*/


public class FileMain03 {


public static void main(String[] args) {

try (InputStream in = new FileInputStream("temp/original.txt");

OutputStream out = new FileOutputStream("temp/good2.txt");) {

int data = 0;

int byteCopied = 0;

while (true) {

data = in.read();

if (data == -1){

break;

}

out.write(data);

byteCopied++;

} // end while (true)

} catch (Exception e) {

}


} // end main()


} // end class FileMain03 



3. 버퍼 스트림을 이용한 파일 입출력


* FileMain05.java


package edu.java.file05;


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;


public class FileMain05 {


public static void main(String[] args) {

InputStream in = null;

BufferedInputStream bin = null;

OutputStream out = null;

BufferedOutputStream bout = null;

try {

// HDD를 접근하는 FileInputStream 객체 생성

in = new FileInputStream("temp/big_text.txt");

// 메모리 버퍼를 접근하는 BufferedInputStream 객체 생성

bin = new BufferedInputStream(in);

// HDD를 직접 접근하는 FileOutputStream 객체 생성

out = new FileOutputStream("temp/big3.txt");

// 메모리 버퍼를 접근하는 BufferedOutputStream 객체 생성

bout = new BufferedOutputStream(out);

// 1바이트씩 읽고 씀.

int data = 0; // 읽은 데이터

int byteCopied = 0; // 복사된 바이트

long startTime = System.currentTimeMillis(); // 현재 시간

while(true) {

// 메모리 버퍼에서 1바이트 읽음

data = bin.read();

if ( data == -1){

break;

}

bout.write(data);

byteCopied++;

} // end while

long endTime = System.currentTimeMillis(); // 끝난 시간

System.out.println("복사 시간 : " + (endTime - startTime) * 0.001);

System.out.println("복사된 데이터: " + byteCopied);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

// 리소스(bin)를 해제할 때는 최종적으로 생성된 리소스만 해제하면,

// 그 리소스(bin)가 사용하고 있던 다른 리소스들도 순차적으로 해제됨

bin.close();

bout.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}

} // end main()


} // end class FileMain05 



* 출력화면

복사 시간 : 0.068

복사된 데이터: 1978086 




Comments