본문 바로가기
Back-End/Java

File I/O : FileOutputStream

by sharekim 2021. 4. 1.

Java를 학습한 지 적어도 4개월이 지난 것 같습니다.

 

그 중 File I/O에 대한 부분이 기억이 나지 않는데,

앞으로 입사할 회사에서 사용할 것 같은 부분을 개인적으로 공부해보려 합니다.

 

가장 기초적인 것으로 FileOutputStream을 이용해서 txt파일로 출력해보겠습니다.

 

public class FileTest {

    public static void main(String[] args) throws IOException {
        test();
    }

    public static void test() throws IOException{
        FileOutputStream out = new FileOutputStream("C:/Users/sksya/Desktop/out.txt");
        for (int i = 0; i < 11; i++) {
            String data = i + "번째 줄입니다\r\n";
            out.write(data.getBytes());
        }

        out.close();
    }
}

 

최근 객체지향에 대해 공부하다 보니 main으로 간단히 작성해도 될 것을 메인과 한 개의 메서드로 구성하게 되었습니다.

(지금 왜 이렇게 작성했나 싶은데 어차피... 공부할려고 혼자 만든 거니 그냥 씁니다)

 

 

 

 

구글링을 해보니 FileOutputStream의 close 메서드와 관련한 의견을 찾을 수 있었는데...

 

더보기
위의 예에서보면 output.close()라는 문장이 있는데 이것은 사용한 파일 객체를 닫아주는 것이다. 사실 이 문장은 생략해도 된다. 왜냐하면 자바 프로그램이 종료할 때 사용한 파일 객체를 자동으로 닫아주기 때문이다. 하지만 직접 사용한 파일을 닫아주는 것이 좋다. 사용했던 파일을 닫지 않고 다시 사용하려고 할 경우에는 에러가 발생할 수 있기 때문이다. .... <출처 : 점프 투 자바>

자동으로 close를 해주긴 하지만, close 전 다시 사용하려는 경우 에러가 발생할 수 있어 의도적으로 close를 해주는 게 좋을 것 같습니다.

 

 

 

 

FileOutputStream.java에서 FileOutputStream 생성자를 살펴봅니다.

public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }
  • Creates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.
  • First, if there is a security manager, its checkWrite method is called with name as its argument.
    If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
  • Params:
    name – the system-dependent filename
  • Throws:

    FileNotFoundException –
     if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

    SecurityException – 
    if a security manager exists and its checkWrite method denies write access to the file.
    See Also: SecurityManager.checkWrite(String)
  1. 파라미터인 name이 파일 이름이 됩니다.
  2. 파일이 없지만 만들 수 없는 경우나, 기타 등등의 사유가 발생한 경우 FileNotFoundException이 발생합니다.
  3. Security manager가 존재하지만 checkWrite 메서드가 파일에 작성하는 것을 거부한 경우 SecurityException이 발생합니다.

 

'Back-End > Java' 카테고리의 다른 글

File I/O : FileInputStream, BufferedReader  (0) 2021.04.02
File I/O : FileWriter 로 내용 추가하기  (0) 2021.04.02
File I/O : FileWriter, PrintWriter  (0) 2021.04.02

댓글