본문 바로가기

Java

자바 메모장 파일 작성하기 (FileOutputStream)

저번에 이어서 이번 글에서 알아볼 것은 FileOutputStream입니다.


FileOutputStream으로 파일을 작성하기

먼저  FileOutputStream  은 파일을 작성하기 위해서 사용한다.

 write()  은 내용을 추가해 주는 역할을 한다.

 

2개의 텍스트 파일

실행하기 전에 files패키지에는 2개의 텍스트 파일밖에 없다.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamEx {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		
		String text = "Test Message\r\nOK?";
		
		//내보낼 경로와 이름을 지정한다.
		FileOutputStream fos = new FileOutputStream(new File("./src/files/FileOutputStreamTest파일.txt"));
		
		//FileOutputStream은 값을 사용할 때는 byte로 변환하여 사용해야 합니다.
		byte[] buf = text.getBytes();
		fos.write(buf); //내용을 입력한다.
		
		fos.flush(); //버퍼의 내용을 비우는 역할을 한다.
		fos.close(); //FileOutputStream을 닫아준다. (중요!)
	}

}

 

여기서 중요한 부분은  FileOutputStream  를 사용했으면  close()  메소드를 통해 닫아주는 게 중요하다.

실행을 하고 나서 확인을 해보면 

FileOutputStreamTest파일.txt가 추가되었다.
내용도 잘 추가되었다.

FileOutputStreamTest파일.txt가 추가된 모습이 보인다.


FileOutputStream으로 내용을 누적해서 작성하기

 new FileOutputStream(경로, true 으로 누적해서 작성할 수 있다. (기본은 false)

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamEx2 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		String text = "Test Message2\r\n";
		
		File file = new File("./src/files/FileOutputStreamTest파일2.txt");
		FileOutputStream fos = new FileOutputStream(file, true);

		byte[] buf = text.getBytes();
		
		fos.write(buf);

		fos.flush();
		fos.close();
	}

}

 

위 코드를 여러 번 실행해서 생성된 텍스트 파일을 보면

10번 입력됬다.

텍스트 파일에 "Test Message2"가 여러번 입력된 것을 볼 수 있다.

 

이 외에 다른  FileWriter  BufferedWriter  를 통해서 입력할 수 있다.