파일 입출력

Nak Jun Choi·2022년 11월 14일

InputStream, OutputStream

  • 스트림은 단방향으로만 데이터를 전송할 수 있기에, 입력과 출력을 동시에 처리하기 위해서는 각각의 스트림이 필요하다.
  • 입출력 스트림은 어떤 대상을 다루느냐에 따라 종류가 나뉜다.

FileInputStream

import java.io.FileInputStream;
  
public class FileInputStreamExample {
    public static void main(String args[])
    {
        try {
            FileInputStream fileInput = new FileInputStream("codestates.txt");
            int i = 0;
            while ((i = fileInput.read()) != -1) { //fileInput.read()의 리턴값을 i에 저장한 후, 값이 -1인지 확인합니다.
                System.out.print((char)i);
            }
            fileInput.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
  • BufferedInputStream 보조 스트림을 사용하면 성능이 향상된다. 버퍼란 바이트 배열로서, 여러 바이트를 저장하여 한 번에 많은 양의 데이터를 입출력할 수 있도록 도와주는 임시 저장 공간이다.

FileOutputStream

import java.io.FileOutputStream;
  
public class FileOutputStreamExample {
    public static void main(String args[]) {
        try {
            FileOutputStream fileOutput = new FileOutputStream("codestates.txt");
            String word = "code";

            byte b[] = word.getBytes();
            fileOutput.write(b);
            fileOutput.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
  • 디렉토리에 code라는 문자열이 입력된 codestate.txt 파일이 생성된다.

FileReader / FileWriter

  • FileInputStream 과 OutputStream은 바이트 기반 스트림이다. 바이트 기반은 입출력 단위가 1byte라는 뜻이다. 하지만 java에서 char 타입은 2byte이다. 따라서 이를 해결하기 위해 문자 기반 스트림을 제공한다. 문자 기반 스트림에는 FileReader과 FileWriter가 있다.

FileReader

public class FileReaderExample {
    public static void main(String args[]) {
        try {
            String fileName = "codestates.txt";
            FileReader file = new FileReader(fileName);

            int data = 0;

            while((data=file.read()) != -1) {
                System.out.print((char)data);
            }
            file.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 버퍼
public class BufferedReaderExample {
    public static void main(String args[]) {
        try {
            String fileName = "codestates.txt";
            FileReader file = new FileReader(fileName);
            BufferedReader buffered = new BufferedReader(file);

            int data = 0;

            while((data=buffered.read()) != -1) {
                System.out.print((char)data);
            }
            file.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileWriter

public class FileWriterExample {
    public static void main(String args[]) {
        try {
            String fileName = "codestates.txt";
            FileWriter writer = new FileWriter(fileName);

            String str = "written!";
            writer.write(str);
            writer.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

File

  • 자바에서는 File 클래스로 파일과 디렉토리에 접근할 수 있다.
import java.io.*;

public class FileExample {
    public static void main(String args[]) throws IOException {
            File file = new File("../codestates.txt");

            System.out.println(file.getPath());
            System.out.println(file.getParent());
            System.out.println(file.getCanonicalPath());
            System.out.println(file.canWrite());
    }
}
  • 파일 인스턴스를 생성하는 것이 파일을 생성하는 것은 아니다. 파일을 생성하기 위해서는 파일 인스턴스를 생성할 때 다음과 같이 첫 번째 인자에 경로를, 두 번쨰 인자에 파일명을 작성하고, createNewFile()를 호출해주어야 한다.
File file = new File("./", "newCodestates.txt");
file.createNewFile();
  • 현재 디렉토리에서 확장자가 .txt인 파일만을 대상으로, 파일명 앞에 "code"라는 문자열을 붙여주는 예제이다.
import java.io.File;

public class FileClassExample {
    public static void main(String[] args) {

        File parentDir = new File("./");
        File[] list = parentDir.listFiles();

        String prefix = "code";

        for(int i =0; i <list.length; i++) {
            String fileName = list[i].getName();

						if(fileName.endsWith("txt") && !fileName.startsWith("code")) {
                list[i].renameTo(new File(parentDir, prefix + fileName));
            }
        }
    }
}
profile
HelloWorld

0개의 댓글