FileOutputStream

- 데이터를 파일 시스템의 파일에 바이트 스트림으로 저장하기 위해 사용된다.

- OutputStream 클래스의 하위 클래스

- 기본적으로 파일이 없으면 생성하고, 이미 존재하면 그 파일에 덮어씀으로 기존 내용은 사라진다.

import java.io.FileOutputStream;

public class Ex17_FileOutputStream {

	public static void main(String[] args) {
		String pathname = "test.txt";
		FileOutputStream fos = null;
		int data;
		
		try {
			// fos = new FileOutputStream(pathname);
				// 없으면 만들고, 파일이 존재하면 지우고 새로 만든다.
			
			fos = new FileOutputStream(pathname, true);
				// 없으면 만들고, 파일이 존재하면 기존 파일을 지우지 않고 추가(append)한다.
			
			System.out.println("내용 입력[종료:Ctrl+z]");
			while( (data = System.in.read()) != -1) {
				fos.write(data);
			}
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(fos != null) {
				try {
					fos.close();
				} catch (Exception e2) {
				}
			}
		}

	}

}

FileOutputStream(String name); 

name이 없으면 만들고, 파일이 존재하면 지우고 새로 만든다.

FileOutputStream(String name, ture); 

name이 없으면 만들고, 파일이 존재하면 기존 파일을 지우지 않고 추가.

+ Recent posts