FlowerBombs

파일 입출력(File Class/InputStream/OutputStream/HelperClass) (!) 본문

JAVA

파일 입출력(File Class/InputStream/OutputStream/HelperClass) (!)

CitronLemon 2019. 3. 1. 22:33

파일 입출력


java.io.File 클래스

파일이나 폴더에 대한 정보를 제공하는 클래스


객체 생성하기

대상의 절대 경로를 통해 객체를 생성하는 경우

1
File file = new File("C:/photo/food.jpg");
cs



상대경로를 통해 객체를 생성하는 경우

1
File file = new File("../food.jpg");
cs



폴더와 파일이름을 나누어서 생성자에 전달하는 경우

1
File file = new File("C:/photo""food.jpt");
cs


주어진 경로의 파일이나 폴더가 실제로 존재하지 않아도 객체 생성 가능




★File 클래스의 메서드

 메서드 

 설명 

 boolean isFile() 

 존재하지 않거나 폴더인 경우 false 리턴

 boolean isDirectory()

 존재하지 않거나 파일인 경우 false 리턴 

 boolean isHidden()

 숨김파일/폴더인지 검사

 String getAbsolutePath()

 절대경로 값을 추출

 boolean mkdirs()

 폴더 생성하기

 boolean delete()

 삭제하기






Stream이란?


- 디바이스의 종류에 구애받지 않고 일관된 방식으로 입출력이 수행되도록 추상화 된 형태.

- 데이터를 byte[] 형식으로 변환한 상태를 의미한다.



java.io.OutputStream

- 스트림 데이터를 프로그램 외부로 내보내는 기능을 제공하는 인터페이스

- 파일 쓰기 기능을 제공하기 위해서 FileOutputStream 클래스에 상속되어 있다.

- 파일 외의 형태로 데이터를 내보내기 위해 ByteArrayOutputStream에도 상속되어 있다.

  (ex. 네트워크를 통한 송출 기능)



FileOutputStream을 통한 파일 쓰기 패턴


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
final String PATH = "K:/test.txt";    // 저장할 파일의 경로
String write_string = "가나다라마바사abcdeft"// 파일에 저장할 내용
 
/** 특정 인코딩 방식을 적용하여 내용을 스트림으로 변환 */
byte[] buffer = null;
try {
    buffer = write_string.getBytes("utf-8");
catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}
 
/** 파일 저장 절차 시작 */
OutputStream out = null;
try {
    out = new FileOutputStream(PATH);    // 파일쓰기
    out.write(buffer);
catch (FileNotFoundException e) {        // 지정된 경로를 찾을 수 없음
    e.printStackTrace();
catch (IOException e) {                // 파일 저장 실패
    e.printStacktrace();
catch (Exception e) {                    // 알 수 없는 
    e.printStacktrace();
finally {
    if (out != null) {
        try {
            out.close();
        } catch (IOException e){
            e.printStacktrace();
        }
    }
}
cs




java.io.InputStream

- 스트림 데이터를 프로그램 내부로 읽어내는 기능을 제공하는 인터페이스.

- 파일 읽기 기능을 제공하기 위해서 FileInputStream 클래스에 상속되어 있다.

- 파일 외의 형태로 데이터를 가져오기 위해 ByteArrayInputStream에도 상속되어 있다.

  (ex. 네트워크를 통한 수신 기능)


FileOutputStream을 통한 파일 읽기 패턴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
final String PATH = "./test.txt";    // 읽을 파일의 경로
byte[] data = null;                    // 읽은 내용이 담겨질 스트림
String read_string = null;            // 읽은 내용이 저장될 문자열
 
/** 파일 읽기 */
InputStream in = null;
try {
    in = new FileInputStream(PATH);
    data = new byte[in.available()];
    in.read(data);
catch (FileNotFoundException e) {        // 지정된 경로를 찾을 수 없음
    e.printStackTrace();
catch (IOException e) {                // 파일 읽기 실패
    e.printStacktrace();
catch (Exception e) {                    // 알 수 없는 에러
    e.printStacktrace();
finally {
    if ( in != null) {
        try {
            in.close();
        } catch (IOException e){
            e.printStacktrace();
        }
    }
}
 
/** 읽은 내용을 문자열로 변환 */
if (data != null) {
    // 문자열로 변환시에는 저장된 인코딩으로 지정해 
     try {
        read_string = new String data "utf-8");
        System.out.println(read_string);
    } catch (UnsupportedencodingException e) {
        e.printStackTrace();
    }
}
cs





'JAVA' 카테고리의 다른 글

JSON (!)  (0) 2019.03.01
InputStream, OutputStream  (0) 2019.03.01
List (ArrayList)  (0) 2019.03.01
컬렉션 프레임워크  (0) 2019.03.01
날짜처리  (0) 2019.03.01
Comments